Java解压缩文件示例
欢迎来到Java解压文件示例。在上一篇文章中,我们学习了如何在Java中压缩文件和目录,现在我们将解压相同的压缩文件,将其从一个目录解压到另一个输出目录中。
解压 Java 文件
要解压缩一个zip文件,我们需要使用ZipInputStream读取zip文件,然后逐个读取所有的ZipEntry。然后使用FileOutputStream将它们写入文件系统。如果输出目录不存在,我们还需要创建该目录以及zip文件中的任何嵌套目录。这是一个Java解压缩文件的程序,将之前创建的tmp.zip解压缩到输出目录中。
package com.Olivia.files;
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) {
String zipFilePath = "/Users/scdev/tmp.zip";
String destDir = "/Users/scdev/output";
unzip(zipFilePath, destDir);
}
private static void unzip(String zipFilePath, String destDir) {
File dir = new File(destDir);
// create output directory if it doesn't exist
if(!dir.exists()) dir.mkdirs();
FileInputStream fis;
//buffer for read and write data to file
byte[] buffer = new byte[1024];
try {
fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze = zis.getNextEntry();
while(ze != null){
String fileName = ze.getName();
File newFile = new File(destDir + File.separator + fileName);
System.out.println("Unzipping to "+newFile.getAbsolutePath());
//create directories for sub directories in zip
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
//close this ZipEntry
zis.closeEntry();
ze = zis.getNextEntry();
}
//close last ZipEntry
zis.closeEntry();
zis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
一旦程序结束,我们就可以在输出文件夹中获得所有压缩文件的内容,且目录层级结构与原始文件相同。以上程序的输出为:
Unzipping to /Users/scdev/output/.DS_Store
Unzipping to /Users/scdev/output/data/data.dat
Unzipping to /Users/scdev/output/data/data.xml
Unzipping to /Users/scdev/output/data/xmls/project.xml
Unzipping to /Users/scdev/output/data/xmls/web.xml
Unzipping to /Users/scdev/output/data.Xml
Unzipping to /Users/scdev/output/DB.xml
Unzipping to /Users/scdev/output/item.XML
Unzipping to /Users/scdev/output/item.xsd
Unzipping to /Users/scdev/output/ms/data.txt
Unzipping to /Users/scdev/output/ms/project.doc
这就是关于Java解压缩文件示例的全部内容。