在Java中,可以使用java.util.zip
包中的類進行文件的壓縮和解壓縮。以下是一個簡單的示例,演示了如何使用這些類來壓縮和解壓縮文件:
壓縮文件
import java.io.*;
import java.util.zip.*;
public class ZipFileExample {
public static void main(String[] args) {
String inputDir = "path/to/input/directory";
String zipFilePath = "path/to/output.zip";
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
File dir = new File(inputDir);
zipDirectory(dir, zos);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void zipDirectory(File dir, ZipOutputStream zos) throws IOException {
if (!dir.isDirectory()) {
throw new IllegalArgumentException("Input must be a directory");
}
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
zipDirectory(file, zos);
} else {
try (FileInputStream fis = new FileInputStream(file);
ZipEntry ze = new ZipEntry(file.getName())) {
zos.putNextEntry(ze);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
}
}
}
}
}
解壓縮文件
import java.io.*;
import java.util.zip.*;
public class UnzipFileExample {
public static void main(String[] args) {
String zipFilePath = "path/to/input.zip";
String outputDir = "path/to/output/directory";
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputDir + File.separator + fileName);
if (!ze.isDirectory()) {
try (FileOutputStream fos = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
byte[] buffer = new byte[1024];
int length;
while ((length = zis.read(buffer)) > 0) {
bos.write(buffer, 0, length);
}
}
} else {
new File(outputDir + File.separator + fileName).mkdirs();
}
ze = zis.getNextEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
請注意,這些示例僅用于演示目的,并且假設輸入和輸出路徑是正確的。在實際應用中,您可能需要添加額外的錯誤處理和驗證。