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文件。你可以根據需要選擇其中一種方法來使用。