java zip壓縮檔案中文檔名亂碼
阿新 • • 發佈:2019-01-01
最近使用java.util.zipoutputstream發現中文名出現亂碼,一直試著使用new String(filename.getBytes("GBK"),"ISO-8859-1");還是無效。後來查閱資料,java.util.zipoutputstream無法設定字符集,建議使用org.apache.tools.zip.ZipOutputStream,這樣的話可以設定字符集。
try{
//新增ZipEntry,並ZipEntry中寫入檔案流
zipos.putNextEntry(new ZipEntry(fileName));
os=new DataOutputStream(zipos);
InputStream is=new FileInputStream(f);
byte[] b = new byte[100];
int length = 0;
while((length = is.read(b))!= -1){
os.write(b, 0, length);
is.close();
zipos.closeEntry();
}catch(Exception e){
e.printStackTrace();
try{
//新增ZipEntry,並ZipEntry中寫入檔案流
zipos.putNextEntry(new ZipEntry(fileName));
os=new DataOutputStream(zipos);
InputStream is=new FileInputStream(f);
byte[] b = new byte[100];
int length = 0;
while((length = is.read(b))!= -1){
os.write(b, 0, length);
}
//這裡就是設定檔案的字符集型別,如果不設定,這樣檔名就很容易出現亂碼
zipos.setEncoding("gbk");is.close();
zipos.closeEntry();
}catch(Exception e){
e.printStackTrace();
}
這樣就可以保證zip中的檔名為中文時不會出現亂碼。