使用 java 模拟 压缩工具,压缩文件夹。例如把D:\abc 目录下的所有文件压缩。
/****
* filedir to zip dir
*
* @param inputFileName 要压缩的文件
* @param zipFileName 创建的压缩文件
* @throws Exception
*/
public void zip(String inputFileName, String zipFileName) throws Exception {
zipFile(zipFileName, new File(inputFileName));
}
/****
*
* @param zipFileName
* @param inputFile
* @throws Exception
*/
private void zipFile(String zipFileName, File inputFile) throws Exception {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(new File(zipFileName));
zipOutput.setEncoding("GBK");//防止压缩文件名为中文乱码问题
zipProcess(zipOutput, inputFile, null);
zipOutput.closeArchiveEntry();
zipOutput.close();
}
/***
* zip to file process
*
* @param zipOutput
* @param inputFile
* @param entry
* @throws IOException
*/
private void zipProcess(ZipArchiveOutputStream zipOutput, File inputFile, ZipArchiveEntry entry) throws IOException {
if (null != inputFile && null != zipOutput) {
if (inputFile.isDirectory()) {
File[] fls = inputFile.listFiles();
for (int i = 0; i < fls.length; i++) {
zipProcess(zipOutput, fls[i], new ZipArchiveEntry(fls[i].getName()));
}
} else {// this file is file
if (null != entry) {
zipOutput.putArchiveEntry(entry);
FileInputStream in = new FileInputStream(inputFile);
int b;
while ((b = in.read()) != -1) {
zipOutput.write(b);
}
in.close();
}
}
}
}
public static void main(String[] args) throws Exception {
DownloadUploadifyUtil downloadUploadifyUtil = new DownloadUploadifyUtil();
downloadUploadifyUtil.zip("D:\\abc", "d:\\测试_cc.zip");
}