📅  最后修改于: 2023-12-03 15:06:07.569000             🧑  作者: Mango
Java 提供了一种简洁的方式来处理 zip 文件。可以使用 java.util.zip 包中的 ZipInput/OutputStream 类来压缩/解压缩文件。
以下代码演示了如何通过 ZipOutputStream 类压缩指定目录下的所有文件。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFiles {
public static void main(String[] args) throws IOException {
String sourceFilePath = "./source-folder";
String zipFilePath = "./compressed-files.zip";
FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zipOut = new ZipOutputStream(fos);
File fileToZip = new File(sourceFilePath);
zipFile(fileToZip, fileToZip.getName(), zipOut);
zipOut.close();
fos.close();
}
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[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
}
以下代码演示了如何通过 ZipInputStream 类解压缩指定的 zip 文件。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipFiles {
public static void main(String[] args) throws IOException {
String zipFilePath = "./compressed-files.zip";
String destDirectory = "./unzipped-folder";
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
FileInputStream fis = new FileInputStream(zipFilePath);
ZipInputStream zipIn = new ZipInputStream(fis);
ZipEntry zipEntry = zipIn.getNextEntry();
while (zipEntry != null) {
String filePath = destDirectory + File.separator + zipEntry.getName();
if (!zipEntry.isDirectory()) {
extractFile(zipIn, filePath);
} else {
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
zipEntry = zipIn.getNextEntry();
}
zipIn.close();
fis.close();
}
private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
FileOutputStream fos = new FileOutputStream(filePath);
byte[] bytes = new byte[1024];
int length;
while ((length = zipIn.read(bytes)) >= 0) {
fos.write(bytes, 0, length);
}
fos.close();
}
}
通过以上两个例子,可以看出 Java 提供的 zip 压缩/解压缩函数非常方便、易用。