/**
*
*
* @param resourcesPath
* @throws Exception
*/
public static void createZipFile(String resourcesPath) {
try {
File fileToZip = new File(resourcesPath);
if (fileToZip.getName().endsWith(".zip")) {
return;
}
FileOutputStream outputStream = new FileOutputStream(fileToZip.getPath() + ".zip");
CheckedOutputStream cos = new CheckedOutputStream(outputStream, new CRC32());
ZipOutputStream out = new ZipOutputStream(cos, StandardCharsets.UTF_8);
zipDirectory(fileToZip, "", out);
out.flush();
out.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 原压缩方法,重复压缩之后,会出现问题,现优化如下<br>
*
*
* @param fileToZip
* @param fileName
* @param zipOut
* @throws IOException
*/
public static void zipDirectory(File fileToZip, String fileName, ZipOutputStream zipOut) {
try {
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
fileName = fileName.length() == 0 ? "" : fileName + "/";
File[] children = fileToZip.listFiles();
for (File childFile : children) {
zipDirectory(childFile, fileName + childFile.getName(), zipOut);
}
return;
}
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}