将某文件夹下的文件压缩成zip

/**
* 将某文件夹下的文件压缩成zip文件
*
* @param filePath 将要被压缩的文件夹 形如 xx\xx\xx.txt 或xx\xx\xx.zip等
 * @param zipOut   zip文件输出流
* @throws IOException
*/
public static void fileToZip(String filePath, ZipOutputStream zipOut){
FileInputStream fileInput = null;
BufferedInputStream bufferStream = null;
try {
// 需要压缩的文件
File file = new File(filePath);
// 获取文件名称,如果有特殊命名需求,可以将参数列表拓展,传fileName
String fileName = file.getName();
fileInput = new FileInputStream(filePath);
// 缓冲
byte[] bufferArea = new byte[1024 * 10];
bufferStream = new BufferedInputStream(fileInput, 1024 * 10);
// 将当前文件作为一个zip实体写入压缩流,fileName代表压缩文件中的文件名称
zipOut.putNextEntry(new ZipEntry(fileName));
int length = 0;
// 最常规IO操作,不必紧张
while ((length = bufferStream.read(bufferArea, 0, 1024 * 10)) != -1) {
zipOut.write(bufferArea, 0, length);
}
// 压缩流不必关闭,使用完后再关
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//关闭流
fileInput.close();
// 需要注意的是缓冲流必须要关闭流,否则输出无效
bufferStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

其中
zipOut = new ZipOutputStream(new FileOutputStream("d:\xx\xx\xx.txt"));
//将2个压缩包合并成一个
zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
ZipUtils.fileToZip(zipRealtionFilePath, zipOut);
ZipUtils.fileToZip(sourceZipPath, zipOut);
posted @ 2021-07-15 14:40  凉了记忆  阅读(482)  评论(0编辑  收藏  举报