在 Java 中,你可以使用多种方式来压缩文件夹。下面我将介绍两种常用的实现方式:使用 Java 内置的 ZipOutputStream 和使用第三方库 Apache Commons Compress。
步骤流程:
示例代码:
import java.io.*;
import java.util.zip.*;
public class ZipFolder {
public static void main(String[] args) {
String sourceFolder = "path/to/source/folder";
String zipFileName = "output.zip";
try {
FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zipOut = new ZipOutputStream(fos);
File fileToZip = new File(sourceFolder);
zipFile(fileToZip, fileToZip.getName(), zipOut);
zipOut.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
File[] children = fileToZip.listFiles();
for (File childFile : children) {
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
}
return;
}
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) >= 0) {
zipOut.write(buffer, 0, length);
}
fis.close();
}
}
步骤流程:
Maven 依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
</dependency>
Gradle 依赖:
implementation 'org.apache.commons:commons-compress:1.21'
示例代码:
import org.apache.commons.compress.archivers.zip.*;
import org.apache.commons.compress.utils.IOUtils;
import java.io.*;
public class ZipFolderApacheCommons {
public static void main(String[] args) {
String sourceFolder = "path/to/source/folder";
String zipFileName = "output.zip";
try {
FileOutputStream fos = new FileOutputStream(zipFileName);
ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(fos);
File fileToZip = new File(sourceFolder);
zipFile(fileToZip, fileToZip.getName(), zipOut);
zipOut.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void zipFile(File fileToZip, String fileName, ZipArchiveOutputStream zipOut) throws IOException {
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
File[] children = fileToZip.listFiles();
for (File childFile : children) {
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
}
return;
}
ZipArchiveEntry entry = new ZipArchiveEntry(fileName);
zipOut.putArchiveEntry(entry);
FileInputStream fis = new FileInputStream(fileToZip);
IOUtils.copy(fis, zipOut);
fis.close();
zipOut.closeArchiveEntry();
}
}
以上是使用 Java 内置的 ZipOutputStream 和 Apache Commons Compress 进行文件夹压缩的两种方法。根据你的需求和项目环境,你可以选择其中一种来实现。