加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java ZIP File Example---refernce

发布时间:2020-12-14 06:18:03 所属栏目:Java 来源:网络整理
导读:In this tutorial we are going to see how to ZIP a file in Java. ZIP is an archive file format that enables data compression and it is mostly used on files and folders. A ZIP file may contain one or more compressed files or folders. Many co

In this tutorial we are going to see how to ZIP a file in Java. ZIP is an archive file format that enables data compression and it is mostly used on files and folders. A ZIP file may contain one or more compressed files or folders. Many compression algorithms have been used by several ZIP implementations,which are ubiquitous in many platforms. It is also possible to store a file in a ZIP archive file without compressing it.

Let’s start with a simple example of adding a single file to a ZIP archive.

1. Add a single file to a ZIP archive

In this example we are adding a regular file to a ZIP archive using??utility classes.

ZipFileExample.java:

<span style="color: #0000ff;">import java.io.*<span style="color: #000000;">;
<span style="color: #0000ff;">import<span style="color: #000000;"> java.util.zip.ZipEntry;
<span style="color: #0000ff;">import<span style="color: #000000;"> java.util.zip.ZipOutputStream;

<span style="color: #0000ff;">public <span style="color: #0000ff;">class<span style="color: #000000;"> ZipFileExample {

</span><span style="color: #0000ff;"&gt;private</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;final</span> String INPUT_FILE = "C:UsersnikosDesktopTestFilestestFile.txt"<span style="color: #000000;"&gt;;
</span><span style="color: #0000ff;"&gt;private</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;final</span> String OUTPUT_FILE = "C:UsersnikosDesktopTestFilestestFile.zip"<span style="color: #000000;"&gt;;

</span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; main(String[] args) {

    zipFile(</span><span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; File(INPUT_FILE),OUTPUT_FILE);

}

</span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; zipFile(File inputFile,String zipFilePath) {
    </span><span style="color: #0000ff;"&gt;try</span><span style="color: #000000;"&gt; {

        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; Wrap a FileOutputStream around a ZipOutputStream
        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; to store the zip stream to a file. Note that this is
        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; not absolutely necessary</span>
        FileOutputStream fileOutputStream = <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; FileOutputStream(zipFilePath);
        ZipOutputStream zipOutputStream </span>= <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; ZipOutputStream(fileOutputStream);

        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; a ZipEntry represents a file entry in the zip archive
        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; We name the ZipEntry after the original file's name</span>
        ZipEntry zipEntry = <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; ZipEntry(inputFile.getName());
        zipOutputStream.putNextEntry(zipEntry);

        FileInputStream fileInputStream </span>= <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; FileInputStream(inputFile);
        </span><span style="color: #0000ff;"&gt;byte</span>[] buf = <span style="color: #0000ff;"&gt;new</span> <span style="color: #0000ff;"&gt;byte</span>[1024<span style="color: #000000;"&gt;];
        </span><span style="color: #0000ff;"&gt;int</span><span style="color: #000000;"&gt; bytesRead;

        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; Read the input file by chucks of 1024 bytes
        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; and write the read bytes to the zip stream</span>
        <span style="color: #0000ff;"&gt;while</span> ((bytesRead = fileInputStream.read(buf)) > 0<span style="color: #000000;"&gt;) {
            zipOutputStream.write(buf,</span>0<span style="color: #000000;"&gt;,bytesRead);
        }

        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; close ZipEntry to store the stream to the file</span>

<span style="color: #000000;"> zipOutputStream.closeEntry();

        zipOutputStream.close();
        fileOutputStream.close();

        System.out.println(</span>"Regular file :" + inputFile.getCanonicalPath()+" is zipped to archive :"+<span style="color: #000000;"&gt;zipFilePath);

    } </span><span style="color: #0000ff;"&gt;catch</span><span style="color: #000000;"&gt; (IOException e) {
        e.printStackTrace();
    }

}

}

The code is pretty self explanatory,but let’s go through each step:

  • First we wrap a?FileOutputStream?around a?ZipOutputStream?to store the zip stream to a file. Note that this is not absolutely necessary,as you can redirect the?ZipOutputStream?to any other stream destination you like,e.g a socket.
  • Then we create a new?ZipEntry?that represents a file entry in the zip archive. We append this entry to the zip output stream. This is necessary as a zip entry marks the begging and ending of each file or folder that is archived in the zip file. It is also important to name that entry,so that you know how to later unzip it.
  • We create a?FileInputStream?to read the input file in chucks f 1024 bytes.
  • We then append those bytes to to zip output stream.
  • We close the?ZipEntry. This positions the stream’s “cursor” at the end of this entry,preparing it to receive a new zip entry.

Now if we run the above code this is the?output:

Regular file :C:UsersnikosDesktopTestFilestestFile.txt is zipped to archive :C:UsersnikosDesktopTestFilestestFile.zip

Here is the folder before zipping this single file:

beforezipping.zip

And this is after zipping “testFile.txt” :

afterZip

2.?Add a single folder to a ZIP archive

Now let’s see how you can add a simple folder,that contains only files to a zip archive.

ZipFileExample.java:

<span style="color: #0000ff;">import<span style="color: #000000;"> org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;

<span style="color: #0000ff;">import java.io.*<span style="color: #000000;">;
<span style="color: #0000ff;">import<span style="color: #000000;"> java.net.URI;
<span style="color: #0000ff;">import<span style="color: #000000;"> java.util.zip.ZipEntry;
<span style="color: #0000ff;">import<span style="color: #000000;"> java.util.zip.ZipOutputStream;

<span style="color: #0000ff;">public <span style="color: #0000ff;">class<span style="color: #000000;"> ZipFileExample {

</span><span style="color: #0000ff;"&gt;private</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;final</span> String INPUT_FOLDER = "C:UsersnikosDesktopTestFiles"<span style="color: #000000;"&gt;;
</span><span style="color: #0000ff;"&gt;private</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;final</span> String ZIPPED_FOLDER = "C:UsersnikosDesktopTestFiles.zip"<span style="color: #000000;"&gt;;

</span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; main(String[] args) {
    zipSimpleFolder(</span><span style="color: #0000ff;"&gt;new</span> File(INPUT_FOLDER),""<span style="color: #000000;"&gt;,ZIPPED_FOLDER);
}

</span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; zipSimpleFolder(File inputFolder,String parentName,String zipFilePath ){

    </span><span style="color: #0000ff;"&gt;try</span><span style="color: #000000;"&gt; {
        FileOutputStream fileOutputStream </span>= <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; FileOutputStream(zipFilePath);

        ZipOutputStream zipOutputStream </span>= <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; ZipOutputStream(fileOutputStream);

        String myname </span>= parentName +inputFolder.getName()+""<span style="color: #000000;"&gt;;

        ZipEntry folderZipEntry </span>= <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; ZipEntry(myname);
        zipOutputStream.putNextEntry(folderZipEntry);

        File[] contents </span>=<span style="color: #000000;"&gt; inputFolder.listFiles();

        </span><span style="color: #0000ff;"&gt;for</span><span style="color: #000000;"&gt; (File f : contents){
            </span><span style="color: #0000ff;"&gt;if</span><span style="color: #000000;"&gt; (f.isFile())
                zipFile(f,myname,zipOutputStream);
        }

        zipOutputStream.closeEntry();
        zipOutputStream.close();

    } </span><span style="color: #0000ff;"&gt;catch</span><span style="color: #000000;"&gt; (FileNotFoundException e) {
        e.printStackTrace();
    } </span><span style="color: #0000ff;"&gt;catch</span><span style="color: #000000;"&gt; (IOException e) {
        e.printStackTrace();
    }

}

</span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; zipFile(File inputFile,ZipOutputStream zipOutputStream) {

    </span><span style="color: #0000ff;"&gt;try</span><span style="color: #000000;"&gt; {
        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; A ZipEntry represents a file entry in the zip archive
        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; We name the ZipEntry after the original file's name</span>
        ZipEntry zipEntry = <span style="color: #0000ff;"&gt;new</span> ZipEntry(parentName+<span style="color: #000000;"&gt;inputFile.getName());
        zipOutputStream.putNextEntry(zipEntry);

        FileInputStream fileInputStream </span>= <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; FileInputStream(inputFile);
        </span><span style="color: #0000ff;"&gt;byte</span>[] buf = <span style="color: #0000ff;"&gt;new</span> <span style="color: #0000ff;"&gt;byte</span>[1024<span style="color: #000000;"&gt;];
        </span><span style="color: #0000ff;"&gt;int</span><span style="color: #000000;"&gt; bytesRead;

        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; Read the input file by chucks of 1024 bytes
        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; and write the read bytes to the zip stream</span>
        <span style="color: #0000ff;"&gt;while</span> ((bytesRead = fileInputStream.read(buf)) > 0<span style="color: #000000;"&gt;) {
            zipOutputStream.write(buf,bytesRead);
        }

        </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; close ZipEntry to store the stream to the file</span>

<span style="color: #000000;"> zipOutputStream.closeEntry();

        System.out.println(</span>"Regular file :" + inputFile.getCanonicalPath()+" is zipped to archive :"+<span style="color: #000000;"&gt;ZIPPED_FOLDER);

    } </span><span style="color: #0000ff;"&gt;catch</span><span style="color: #000000;"&gt; (IOException e) {
        e.printStackTrace();
    }

}

}

The basic goal here is to zip a folder that contains only flat files. An important thing to notice here is that we create ZipEntry for the folder and add it to the archive. Then we create a Zip entry for each file in the folder. After zipping all the files in the folder and having created and closed all file zip entries we finally close the zip entry of the folder. Another important thing to notice is that we’ve added aparentName?argument in the methods. That is basically to easily calculate the absolute path of each file in order to place it in the correct folder in the archive. Our situation here is very simple as we have only one parent folder in the archive.

Now if we run the above code this is the?output:

Regular file :TestFilestestFile.txt is zipped to archive :C:UsersnikosDesktopTestFiles.zip

Here is the zipped folder :

zipped-folder

And you can see that it contains a singe file:

contents

3.?Add a complete directory tree to a ZIP archive

In this section we are going to add a complete directory tree in the archive. This means that our parent directory might not only contain flat files,but a folder as well,which in turn might contain other files and folders etc.

Let’s see a recursive solution:

ZipFileExample.java:

<span style="color: #0000ff;">import<span style="color: #000000;"> java.io.File;
<span style="color: #0000ff;">import<span style="color: #000000;"> java.io.FileNotFoundException;
<span style="color: #0000ff;">import<span style="color: #000000;"> java.io.FileOutputStream;
<span style="color: #0000ff;">import<span style="color: #000000;"> java.io.FileInputStream;
<span style="color: #0000ff;">import<span style="color: #000000;"> java.io.IOException;
<span style="color: #0000ff;">import<span style="color: #000000;"> java.util.zip.ZipEntry;
<span style="color: #0000ff;">import<span style="color: #000000;"> java.util.zip.ZipOutputStream;

<span style="color: #0000ff;">public <span style="color: #0000ff;">class<span style="color: #000000;"> ZipFileExample {

</span><span style="color: #0000ff;"&gt;private</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;final</span> String INPUT_FOLDER = "C:UsersnikosDesktopTestFiles"<span style="color: #000000;"&gt;;
</span><span style="color: #0000ff;"&gt;private</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;final</span> String ZIPPED_FOLDER = "C:UsersnikosDesktopTestFiles.zip"<span style="color: #000000;"&gt;;

</span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; main(String[] args) {

    </span><span style="color: #0000ff;"&gt;try</span><span style="color: #000000;"&gt; {

        zip( INPUT_FOLDER,ZIPPED_FOLDER);

    } </span><span style="color: #0000ff;"&gt;catch</span><span style="color: #000000;"&gt; (IOException e) {
        e.printStackTrace();
    }

}

</span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;void</span> zip(String inputFolder,String targetZippedFolder)  <span style="color: #0000ff;"&gt;throws</span><span style="color: #000000;"&gt; IOException {

    FileOutputStream fileOutputStream </span>= <span style="color: #0000ff;"&gt;null</span><span style="color: #000000;"&gt;;

    fileOutputStream </span>= <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; FileOutputStream(targetZippedFolder);
    ZipOutputStream zipOutputStream </span>= <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; ZipOutputStream(fileOutputStream);

    File inputFile </span>= <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; File(inputFolder);

    </span><span style="color: #0000ff;"&gt;if</span><span style="color: #000000;"&gt; (inputFile.isFile())
        zipFile(inputFile,</span>""<span style="color: #000000;"&gt;,zipOutputStream);
    </span><span style="color: #0000ff;"&gt;else</span> <span style="color: #0000ff;"&gt;if</span><span style="color: #000000;"&gt; (inputFile.isDirectory())
        zipFolder(zipOutputStream,inputFile,</span>""<span style="color: #000000;"&gt;);

    zipOutputStream.close();
}

</span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;void</span> zipFolder(ZipOutputStream zipOutputStream,File inputFolder,String parentName)  <span style="color: #0000ff;"&gt;throws</span><span style="color: #000000;"&gt; IOException {

    String myname </span>= parentName +inputFolder.getName()+""<span style="color: #000000;"&gt;;

    ZipEntry folderZipEntry </span>= <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; ZipEntry(myname);
    zipOutputStream.putNextEntry(folderZipEntry);

    File[] contents </span>=<span style="color: #000000;"&gt; inputFolder.listFiles();

    </span><span style="color: #0000ff;"&gt;for</span><span style="color: #000000;"&gt; (File f : contents){
        </span><span style="color: #0000ff;"&gt;if</span><span style="color: #000000;"&gt; (f.isFile())
            zipFile(f,zipOutputStream);
        </span><span style="color: #0000ff;"&gt;else</span> <span style="color: #0000ff;"&gt;if</span><span style="color: #000000;"&gt;(f.isDirectory())
            zipFolder(zipOutputStream,f,myname);
    }
    zipOutputStream.closeEntry();
}

</span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;void</span> zipFile(File inputFile,ZipOutputStream zipOutputStream) <span style="color: #0000ff;"&gt;throws</span><span style="color: #000000;"&gt; IOException{

    </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; A ZipEntry represents a file entry in the zip archive
    </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; We name the ZipEntry after the original file's name</span>
    ZipEntry zipEntry = <span style="color: #0000ff;"&gt;new</span> ZipEntry(parentName+<span style="color: #000000;"&gt;inputFile.getName());
    zipOutputStream.putNextEntry(zipEntry);

    FileInputStream fileInputStream </span>= <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; FileInputStream(inputFile);
    </span><span style="color: #0000ff;"&gt;byte</span>[] buf = <span style="color: #0000ff;"&gt;new</span> <span style="color: #0000ff;"&gt;byte</span>[1024<span style="color: #000000;"&gt;];
    </span><span style="color: #0000ff;"&gt;int</span><span style="color: #000000;"&gt; bytesRead;

    </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; Read the input file by chucks of 1024 bytes
    </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; and write the read bytes to the zip stream</span>
    <span style="color: #0000ff;"&gt;while</span> ((bytesRead = fileInputStream.read(buf)) > 0<span style="color: #000000;"&gt;) {
        zipOutputStream.write(buf,bytesRead);
    }

    </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; close ZipEntry to store the stream to the file</span>

<span style="color: #000000;"> zipOutputStream.closeEntry();

    System.out.println(</span>"Regular file :" + parentName+inputFile.getName() +" is zipped to archive :"+<span style="color: #000000;"&gt;ZIPPED_FOLDER);
}

}

As you can see inside?zipFolder?method we simply add a recursive call if the file we are trying to zip is a directory. That’s it. Notice that we create our?ZipOutputStream?to the top level zip method,so that all methods calls from then on can use the same instance of that stream. If we left the code as before,every time zipFolder was called,a new?ZipOutputStream?would be created,something that we definitely don’t want.

To test this,I’ve copied an Eclipse Project folder in my?TestFiles?folder.

Now if we run the above code this is the?output:

Regular file :TestFilesEJBInterceptorEJBInterceptorEAR.project is zipped to archive :C:UsersnikosDesktopTestFiles.zip
Regular file :TestFilesEJBInterceptorEJBInterceptorEAR.settingsorg.eclipse.wst.common.component is zipped to archive :C:UsersnikosDesktopTestFiles.zip
Regular file :TestFilesEJBInterceptorEJBInterceptorEAR.settingsorg.eclipse.wst.common.project.facet.core.xml is zipped to archive :C:UsersnikosDesktopTestFiles.zip
Regular file :TestFilesEJBInterceptorEJBInterceptorEAREarContentMETA-INFapplication.xml is zipped to archive :C:UsersnikosDesktopTestFiles.zip
Regular file :TestFilesEJBInterceptorInterceptorsEJB.classpath is zipped to archive :C:UsersnikosDesktopTestFiles.zip
Regular file :TestFilesEJBInterceptorInterceptorsEJB.project is zipped to archive :C:UsersnikosDesktopTestFiles.zip
Regular file :TestFilesEJBInterceptorInterceptorsEJB.settingsorg.eclipse.jdt.core.prefs is zipped to archive :C:UsersnikosDesktopTestFiles.zip
Regular file :TestFilesEJBInterceptorInterceptorsEJB.settingsorg.eclipse.wst.common.component is zipped to archive :C:UsersnikosDesktopTestFiles.zip
Regular file :TestFilesEJBInterceptorInterceptorsEJB.settingsorg.eclipse.wst.common.project.facet.core.xml is zipped to archive :C:UsersnikosDesktopTestFiles.zip
Regular file :TestFilesEJBInterceptorInterceptorsEJBbuildclassescomjavacodegeeksenterpriseejbinterceptorSecondInterceptor.class is zipped to archive :C:UsersnikosDesktopTestFiles.zip
Regular file :TestFilesEJBInterceptorInterceptorsEJBbuildclassescomjavacodegeeksenterpriseejbinterceptorSimpleInterceptor.class is zipped to archive :C:UsersnikosDesktopTestFiles.zip
Regular file :TestFilesEJBInterceptorInterceptorsEJBbuildclassescomjavacodegeeksenterpriseejbSimpleEJB.class is zipped to archive :C:UsersnikosDesktopTestFiles.zip
Regular file :TestFilesEJBInterceptorInterceptorsEJBbuildclassesMETA-INFejb-jar.xml is zipped to archive :C:UsersnikosDesktopTestFiles.zip
...

Now you can use this simple?zip?method as a utility to zip a normal file or a complete file path.

Here you can see the zipped folder:

zipped-filepath

And from there you can navigate the file path. For example :

walkthourgh

4.?Compressing files

java.util.zip?basically offers two methods to compressed the files that you add in the archive: STORED and DEFLATED. In STORED method,you basically store the files uncompressed,it just stores the raw bytes. DEFLATED on the other hand uses the??to perform compression on the files. You can specify which compression algorithm you want to use at each individualZipEntry?using setMethod(ZipEntry.STORED) or setMethod(ZipEntry.DEFLATED)?ZipEntry?API methods.

Additionally you can specify other characteristics of the compressed components,to increase security and consistency of the contents of the archive. These include the size of the file and the check sum of the file. For the check sum?java.util.zip?offers a utility to calculate CRC32 checksum of the file. You can then add it to the ZipEntry using its?setCrc?API method. It is not always advisable to compress all the files in DEFLATED mode,because it simply takes more time.

Download Source Code

This was a Java ZIP File Example. You can download the source code of this example here :?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读