1. 程式人生 > >(java)解決檔案是中文名打包成zip檔名稱亂碼的問題。

(java)解決檔案是中文名打包成zip檔名稱亂碼的問題。

1、引人

import org.apache.tools.zip.ZipEntry; 

import org.apache.tools.zip.ZipOutputStream;類

2、方法

/*

billNos:要打包的檔案列表

suffix:字尾名

return 打包檔案路徑

*/

private String packZip(List<String> billNos, String suffix) throws Exception{
byte[] buffer = new byte[1024];
String dir = FileUtils.rootPath + "report/";//檔案所在目錄
File file;
String strZipName = "sample.zip";//名稱
String path = dir + strZipName;//檔案路徑
File file1 = new File(path);

//判斷打包檔案是否存在,如果存在就刪除
if(file1.exists()) {  
file1.delete();
        }
file1.createNewFile();//新建打包檔案
String fileName;
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(path));
out.setEncoding("utf-8");//設定編碼格式
FileInputStream fis;
int len;
for(String s:billNos){
fileName = dir + s+ suffix;//要打包的檔名稱
file = new File(fileName);
fis = new FileInputStream(file);  
out.putNextEntry(new ZipEntry(file.getName()));
while((len = fis.read(buffer))>0){  
out.write(buffer,0,len);   
}
out.closeEntry();  
       fis.close();  
}
 
out.close();//關閉
return "report/" + strZipName;
}