ZipEntry zipEntry=new ZipEntry(basePath + System.getProperties().getProperty("file.separator"));
zipEntry.setUnixMode(755);//解決linux亂碼java
若是是文件,則
ZipEntry zipEntry=new ZipEntry(base);
zipEntry.setUnixMode(644);//解決linux亂碼linux
而後在輸出時強制設置編碼:
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
out.setEncoding("GBK");//解決linux亂碼apache
所有代碼以下:
windows
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;工具
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;編碼
import org.apache.tools.ant.Project; spa
import org.apache.tools.ant.taskdefs.Expand;blog
/**
* 文件夾壓縮,支持win和linux
* @author wlzhang
*
*/
public class ZipUtil
{
/**
* @param inputFileName
* 輸入一個文件夾
* @param zipFileName
* 輸出一個壓縮文件夾,打包後文件名字
* @throws Exception
*/
public static OutputStream zip(String inputFileName, String zipFileName) throws Exception
{
return zip(zipFileName, new File(inputFileName));
}ip
private static OutputStream zip(String zipFileName, File inputFile) throws Exception
{
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
out.setEncoding("UTF-8");//解決linux亂碼 根據linux系統的實際編碼設置,能夠使用命令 vi/etc/sysconfig/i18n 查看linux的系統編碼
zip(out, inputFile, "");
out.close();
return out;
}get
private static void zip(ZipOutputStream out, File f, String base) throws Exception
{
if (f.isDirectory())
{ // 判斷是否爲目錄
File[] fl = f.listFiles();
// out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
// out.putNextEntry(new ZipEntry(base + "/"));
ZipEntry zipEntry=new ZipEntry(base + System.getProperties().getProperty("file.separator"));
zipEntry.setUnixMode(755);//解決linux亂碼
out.putNextEntry(zipEntry);
// base = base.length() == 0 ? "" : base + "/";
base = base.length() == 0 ? "" : base + System.getProperties().getProperty("file.separator");
for (int i = 0; i < fl.length; i++)
{
zip(out, fl[i], base + fl[i].getName());
}
}
else
{ // 壓縮目錄中的全部文件
// out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
ZipEntry zipEntry=new ZipEntry(base);
zipEntry.setUnixMode(644);//解決linux亂碼
out.putNextEntry(zipEntry);
FileInputStream in = new FileInputStream(f);
int b;
while ((b = in.read()) != -1)
{
out.write(b);
}
in.close();
}
}
private static void unzip(String sourceZip,String destDir) throws Exception{
try{
Project p = new Project();
Expand e = new Expand();
e.setProject(p);
e.setSrc(new File(sourceZip));
e.setOverwrite(false);
e.setDest(new File(destDir));
/*
ant下的zip工具默認壓縮編碼爲UTF-8編碼,
而winRAR軟件壓縮是用的windows默認的GBK或者GB2312編碼
因此解壓縮時要制定編碼格式
*/
e.setEncoding("UTF-8"); //根據linux系統的實際編碼設置
e.execute();
}catch(Exception e){
throw e;
}
}
}