在 Java 中解压缩文件
Sheeraz Gul
2023年10月12日
Java
Java Unzip

我们可以使用 Java 中内置的 Zip
API 来提取 zip 文件。本教程演示如何在 Java 中提取 zip 文件。
在 Java 中解压缩文件
java.util.zip
用于解压缩 Java 中的 zip 文件。ZipInputStream
是用于读取 zip 文件并提取它们的主要类。
请按照以下步骤提取 Java 中的 zip 文件。
我们创建了一个函数来获取输入和目标路径并提取文件以实现这些步骤。压缩文件如下。
让我们用 Java 实现上面的方法来提取如图所示的 zip 文件。
Java
javaCopypackage delftstack;
import java.io.BufferedOutputStream;
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 Java_Unzip {
private static final int BUFFER_SIZE = 4096;
public static void unzip(String ZipFilePath, String DestFilePath) throws IOException {
File Destination_Directory = new File(DestFilePath);
if (!Destination_Directory.exists()) {
Destination_Directory.mkdir();
}
ZipInputStream Zip_Input_Stream = new ZipInputStream(new FileInputStream(ZipFilePath));
ZipEntry Zip_Entry = Zip_Input_Stream.getNextEntry();
while (Zip_Entry != null) {
String File_Path = DestFilePath + File.separator + Zip_Entry.getName();
if (!Zip_Entry.isDirectory()) {
extractFile(Zip_Input_Stream, File_Path);
} else {
File directory = new File(File_Path);
directory.mkdirs();
}
Zip_Input_Stream.closeEntry();
Zip_Entry = Zip_Input_Stream.getNextEntry();
}
Zip_Input_Stream.close();
}
private static void extractFile(ZipInputStream Zip_Input_Stream, String File_Path)
throws IOException {
BufferedOutputStream Buffered_Output_Stream =
new BufferedOutputStream(new FileOutputStream(File_Path));
byte[] Bytes = new byte[BUFFER_SIZE];
int Read_Byte = 0;
while ((Read_Byte = Zip_Input_Stream.read(Bytes)) != -1) {
Buffered_Output_Stream.write(Bytes, 0, Read_Byte);
}
Buffered_Output_Stream.close();
}
public static void main(String[] args) throws IOException {
String ZipFilePath = "delftstack.zip";
String DestFilePath = "C:\\Users\\Sheeraz\\eclipse-workspace\\Demos";
unzip(ZipFilePath, DestFilePath);
System.out.println("Zip File extracted Successfully");
}
}
上述代码的输出如下。
textCopyZip File extracted Successfully
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Sheeraz Gul
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook