下文讲述java代码生成zip文件的方法分享,如下所示:
实现思路:
借助ZipOutputStream类对文件进行压缩操作
例:
package com.java265.other;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class test {
/*
* java265.com 使用java代码生成一个压缩包的示例分享
*/
public static void main(String[] args) throws Exception {
compressFileToZip("D:\\test2.txt", "D:\\test2.zip");
}
private static void compressFileToZip(String filePath,
String zipFilePath) {
try (ZipOutputStream z = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
//递归的压缩文件夹和文件
doCompress("", filePath, z);
//
z.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void doCompress(String parentFilePath, String filePath, ZipOutputStream zos) {
File sourceFile = new File(filePath);
if (!sourcefile.exists()) {
return;
}
String zipEntryName = parentFilePath + "/" + sourceFile.getName();
if (parentFilePath.isEmpty()) {
zipEntryName = sourceFile.getName();
}
if (sourceFile.isDirectory()) {
File[] childFiles = sourceFile.listFiles();
if (Objects.isNull(childFiles)) {
return;
}
for (File childFile : childFiles) {
doCompress(zipEntryName, childFile.getAbsolutePath(), zos);
}
} else {
int len = -1;
byte[] buf = new byte[1024];
try (InputStream input = new BufferedInputStream(new FileInputStream(sourceFile))) {
zos.putNextEntry(new ZipEntry(zipEntryName));
while ((len = input.read(buf)) != -1) {
zos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


