借助ZipOutputStream实现文件压缩,这里主要举两个例子,一个例子是单个文件压缩,一个例子是单个文件夹进行压缩
单一文件进行压缩
public static void singleCompress(){
File file = new File("D:/logs/minio-0706/basic-account.2023-07-06.0.log");
String zipFile = "D:/logs/minio-0706.zip";
try(FileInputStream inputStream = new FileInputStream(file);ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile))){
zipOutputStream.putNextEntry(new ZipEntry("basic-account.2023-07-06.0.log"));
IOUtils.copy(inputStream, zipOutputStream);
}catch (Exception e){
e.printStackTrace();
}
}
比较好理解一点的解释就是,将文件流写入到ZipOutputStream就完事了。
ZipEntry是条目的概念,通俗点的解释就是代表了在压缩包内是咋显示的
比如 basic-account.2023-07-06.0.log,那么压缩包内直接显示的就是这个文件
比如 minio/basic-account.2023-07-06.0.log, 那么压缩包内显示看到minio文件夹,再里面一层才是这个日志文件
单一目录进行压缩
public void directoryCompress(){
File sourceFile = new File("D:/logs/minio-0706");
String zipFile = "D:/logs/minio-0706.zip";
String baseDir = "minio-0706/";
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile))) {
for (File file : sourceFile.listFiles()) {
try (FileInputStream inputStream = new FileInputStream(file)) {
zipOutputStream.putNextEntry(new ZipEntry(baseDir + file.getName()));
IOUtils.copy(inputStream, zipOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
}
}
其实就是循环将文件夹下的目录依次写入到ZipOutputStream,唯一重要的就是要定义好每一个ZipEntry(也就是每一个文件在压缩包内的路径)