Java 解压缩文件示例

欢迎来到Java Unzip 文件示例. 在上一篇文章中,我们学到了(/community/tutorials/java-zip-file-folder-example),在这里我们将从目录中创建的相同的 zip 文件解密到另一个输出目录。

Java Unzip 檔案

要解密一个Zip文件,我们需要用ZipInputStream读取Zip文件,然后读取所有ZipEntry一个接一个,然后使用FileOutputStream将其写入文件系统,我们还需要创建输出目录,如果它不存在,以及任何嵌入式目录在Zip文件中。

 1package com.journaldev.files;
 2
 3import java.io.File;
 4import java.io.FileInputStream;
 5import java.io.FileOutputStream;
 6import java.io.IOException;
 7import java.util.zip.ZipEntry;
 8import java.util.zip.ZipInputStream;
 9
10public class UnzipFiles {
11
12    public static void main(String[] args) {
13        String zipFilePath = "/Users/pankaj/tmp.zip";
14
15        String destDir = "/Users/pankaj/output";
16
17        unzip(zipFilePath, destDir);
18    }
19
20    private static void unzip(String zipFilePath, String destDir) {
21        File dir = new File(destDir);
22        // create output directory if it doesn't exist
23        if(!dir.exists()) dir.mkdirs();
24        FileInputStream fis;
25        //buffer for read and write data to file
26        byte[] buffer = new byte[1024];
27        try {
28            fis = new FileInputStream(zipFilePath);
29            ZipInputStream zis = new ZipInputStream(fis);
30            ZipEntry ze = zis.getNextEntry();
31            while(ze != null){
32                String fileName = ze.getName();
33                File newFile = new File(destDir + File.separator + fileName);
34                System.out.println("Unzipping to "+newFile.getAbsolutePath());
35                //create directories for sub directories in zip
36                new File(newFile.getParent()).mkdirs();
37                FileOutputStream fos = new FileOutputStream(newFile);
38                int len;
39                while ((len = zis.read(buffer)) > 0) {
40                fos.write(buffer, 0, len);
41                }
42                fos.close();
43                //close this ZipEntry
44                zis.closeEntry();
45                ze = zis.getNextEntry();
46            }
47            //close last ZipEntry
48            zis.closeEntry();
49            zis.close();
50            fis.close();
51        } catch (IOException e) {
52            e.printStackTrace();
53        }
54
55    }
56
57}

一旦程序完成,我们在输出文件夹中有所有的zip文件内容,具有相同的目录等级。

 1Unzipping to /Users/pankaj/output/.DS_Store
 2Unzipping to /Users/pankaj/output/data/data.dat
 3Unzipping to /Users/pankaj/output/data/data.xml
 4Unzipping to /Users/pankaj/output/data/xmls/project.xml
 5Unzipping to /Users/pankaj/output/data/xmls/web.xml
 6Unzipping to /Users/pankaj/output/data.Xml
 7Unzipping to /Users/pankaj/output/DB.xml
 8Unzipping to /Users/pankaj/output/item.XML
 9Unzipping to /Users/pankaj/output/item.xsd
10Unzipping to /Users/pankaj/output/ms/data.txt
11Unzipping to /Users/pankaj/output/ms/project.doc

这是关于 java unzip 文件的例子。

Published At
Categories with 技术
Tagged with
comments powered by Disqus