Java 解压缩文件示例
欢迎来到 Java 解压文件示例。在上一篇文章中,我们学习了如何在 Java 中压缩文件和目录,在这里我们将从目录创建的相同 zip 文件解压到另一个输出目录。
Java解压缩文件
要解压 zip 文件,我们需要使用 读取 zip 文件,ZipInputStream
然后ZipEntry
逐个读取所有内容。然后使用将它们写入文件系统。如果输出目录不存在,我们还需要创建输出目录以及 zip 文件中存在的任何嵌套目录。以下是将先前创建的文件解压到输出目录的FileOutputStream
Java 解压文件程序。tmp.zip
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
这就是有关 java 解压缩文件示例的全部内容。