21xrx.com
2025-04-03 01:15:07 Thursday
文章检索 我的文章 写文章
Java实现文件夹中部分文件压缩
2023-06-15 14:20:15 深夜i     10     0
Java 文件夹 ZipOutputStream类

在开发过程中,经常会有将文件夹中的部分文件压缩到一起的需求。Java提供了ZipOutputStream类来实现这一功能。ZipOutputStream类是一个输出流,它可以将数据写入到ZIP归档文件中,从而实现压缩。

首先,需要遍历文件夹中的所有文件,将需要压缩的文件加入到ZipOutputStream对象中。具体实现过程如下:

String folderPath = "folder path"; // 文件夹路径
String[] fileNames = "file2.jpg" ; // 需要压缩的文件名
String zipFilePath = "zip file path"; // 压缩后的文件路径
byte[] buffer = new byte[1024];
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFilePath));
for (String fileName : fileNames) {
  File file = new File(folderPath + "\\" + fileName);
  FileInputStream fileInputStream = new FileInputStream(file);
  ZipEntry zipEntry = new ZipEntry(fileName);
  zipOutputStream.putNextEntry(zipEntry);
  
  int length;
  while ((length = fileInputStream.read(buffer)) > 0) {
    zipOutputStream.write(buffer, 0, length);
  }
  
  zipOutputStream.closeEntry();
  fileInputStream.close();
}
zipOutputStream.close();

以上代码将文件夹中的file1.txt和file2.jpg压缩到了一个名为zip file path的文件中。

  
  

评论区

请求出错了