在上一篇文章中,我们向你展示了如何将文件压缩成zip文件格式。在这篇文章中,我们将向你展示如何解压它。本文的例子使用try-with-resources语句来自动关闭资源,并在JDK 8及以后的版本中编译和执行。
ZIP
文件解压文件 示例ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))
FileOutputStream fos = new FileOutputStream(newFile)
在这个例子中,它将从 "C:\Project_Work\samples\dest_sample.zip "中读取一个ZIP文件,并将所有的压缩文件解压到 "C:\Project_Work\samples\outputzip "文件夹。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* This Java program demonstartes that how to decompress files from zip.
* @author javaguides.net
*
*/
public class DecompressZipExample {
List<String> fileList;
private static final String INPUT_ZIP_FILE = "C:\\Project_Work\\samples\\dest_sample.zip";
private static final String OUTPUT_FOLDER = "C:\\Project_Work\\samples\\outputzip";
public static void main(String[] args) {
DecompressZipExample unZip = new DecompressZipExample();
unZip.unZipIt(INPUT_ZIP_FILE, OUTPUT_FOLDER);
}
/**
* Unzip it
*
* @param zipFile
* input zip file
* @param output
* zip file output folder
*/
public void unZipIt(String zipFile, String outputFolder) {
byte[] buffer = new byte[1024];
File folder = new File(OUTPUT_FOLDER);
if (!folder.exists()) {
folder.mkdir();
}
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
// get the zipped file list entry
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
System.out.println("file unzip : " + newFile.getAbsoluteFile());
// create all non exists folders
// else you will hit FileNotFoundException for compressed folder
new File(newFile.getParent()).mkdirs();
try (FileOutputStream fos = new FileOutputStream(newFile)) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
System.out.println("Done");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输出
file unzip : C:\Project_Work\samples\outputzip\sample.txt
file unzip : C:\Project_Work\samples\outputzip\sample1.txt
file unzip : C:\Project_Work\samples\outputzip\sample2.txt
Done
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/07/how-to-decompress-files-from-zip-file-in-java.html
内容来源于网络,如有侵权,请联系作者删除!