Java提供了多种方法来压缩文件夹。下面将介绍两种常用的方法:使用ZipOutputStream和使用Apache Commons Compress库。
1. 使用ZipOutputStream:
import java.io.*;
import java.util.zip.*;
public class ZipFolderExample {
public static void main(String[] args) {
String sourceFolder = "path/to/source/folder";
String zipFile = "path/to/destination/zipfile.zip";
try {
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
zipFolder(sourceFolder, zos);
zos.close();
fos.close();
System.out.println("Folder successfully compressed to " + zipFile);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void zipFolder(String sourceFolder, ZipOutputStream zos) throws IOException {
File folder = new File(sourceFolder);
if (!folder.exists()) {
throw new FileNotFoundException("Folder not found: " + sourceFolder);
}
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
zipFolder(file.getAbsolutePath(), zos);
} else {
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(file);
zos.putNextEntry(new ZipEntry(file.getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
}
}
}
2. 使用Apache Commons Compress库:
import org.apache.commons.compress.archivers.zip.*;
import org.apache.commons.compress.utils.IOUtils;
import java.io.*;
import java.nio.file.*;
public class ZipFolderExample {
public static void main(String[] args) {
String sourceFolder = "path/to/source/folder";
String zipFile = "path/to/destination/zipfile.zip";
try {
FileOutputStream fos = new FileOutputStream(zipFile);
ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos);
zipFolder(sourceFolder, zos);
zos.close();
fos.close();
System.out.println("Folder successfully compressed to " + zipFile);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void zipFolder(String sourceFolder, ZipArchiveOutputStream zos) throws IOException {
File folder = new File(sourceFolder);
if (!folder.exists()) {
throw new FileNotFoundException("Folder not found: " + sourceFolder);
}
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
zipFolder(file.getAbsolutePath(), zos);
} else {
ZipArchiveEntry entry = new ZipArchiveEntry(file, file.getName());
zos.putArchiveEntry(entry);
FileInputStream fis = new FileInputStream(file);
IOUtils.copy(fis, zos);
zos.closeArchiveEntry();
fis.close();
}
}
}
}
以上两种方法都可以将指定的文件夹及其子文件夹压缩为一个ZIP文件。你可以根据需要选择其中一种方法来使用。