更新时间:2022-08-18 10:58:45 来源:极悦 浏览1051次
要解压缩 zip 文件,我们需要读取 zip 文件,ZipInputStream然后ZipEntry一一读取。然后使用FileOutputStream将它们写入文件系统。如果输出目录不存在并且 zip 文件中存在任何嵌套目录,我们还需要创建它。这是解压之前创建tmp.zip的输出目录的java解压缩文件程序。
package com.journaldev.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/pankaj/tmp.zip";
String destDir = "/Users/pankaj/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();
}
}
}
程序完成后,我们在具有相同目录层次结构的输出文件夹中拥有所有 zip 文件内容。上述程序的输出是:
Unzipping to /Users/pankaj/output/.DS_Store
Unzipping to /Users/pankaj/output/data/data.dat
Unzipping to /Users/pankaj/output/data/data.xml
Unzipping to /Users/pankaj/output/data/xmls/project.xml
Unzipping to /Users/pankaj/output/data/xmls/web.xml
Unzipping to /Users/pankaj/output/data.Xml
Unzipping to /Users/pankaj/output/DB.xml
Unzipping to /Users/pankaj/output/item.XML
Unzipping to /Users/pankaj/output/item.xsd
Unzipping to /Users/pankaj/output/ms/data.txt
Unzipping to /Users/pankaj/output/ms/project.doc
0基础 0学费 15天面授
Java就业班有基础 直达就业
业余时间 高薪转行
Java在职加薪班工作1~3年,加薪神器
工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习