在 Java 中解压缩文件
我们可以使用 Java 中内置的 Zip
API 来提取 zip 文件。本教程演示如何在 Java 中提取 zip 文件。
在 Java 中解压缩文件
java.util.zip
用于解压缩 Java 中的 zip 文件。ZipInputStream
是用于读取 zip 文件并提取它们的主要类。
请按照以下步骤提取 Java 中的 zip 文件。
-
使用
ZipInputStream
和FileInputStream
读取 zip 文件。 -
使用
getNextEntry()
方法读取条目。 -
现在使用带有字节的
read()
方法读取二进制数据。 -
使用
closeEntry()
方法关闭条目。 -
最后,关闭 zip 文件。
我们创建了一个函数来获取输入和目标路径并提取文件以实现这些步骤。压缩文件如下。
让我们用 Java 实现上面的方法来提取如图所示的 zip 文件。
package 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");
}
}
上述代码的输出如下。
Zip File extracted Successfully
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。