Java uses basic JDK to operate ZIP files

Source: Internet
Author: User

Tip:

This article briefly introduces the zip interface in JDK. However, the zip operation interface provided by JDK is very imperfect, neither Chinese nor password is supported, so the availability is not high.

If you need to process ZIP files in a Java environment, zip4j, an open-source project, is recommended. zip4j supports multiple encryption and compression algorithms and uses unicode encoding. Therefore, it also supports Chinese characters, other aspects are also very good, which can be said to be powerful.

For details, see another blog:

Http://blog.csdn.net/zhangyihui1986/article/details/7921376

Recently, due to work needs, I have learned some about zip and RAR decompression and compression in the Java language. Now I want to record it for some time. If you can help your friends, I would like to be a great expert.

First, let's talk about the ZIP format:

JDK has already completed the interface (in the java.util.zip package) for operating zipfiles. These interfaces are easy to use and mainly involve
Zipentry // This class is used to indicate ZIP file entries
Zipfile // This class is used to read entries from a zip file
Zipinputstream // input stream for reading files in ZIP Format
Zipoutputstream // This class writes files in ZIP file format to implement output stream
And so on. Some other classes are related to verification, and some do not understand. They are not used in basic usage.

Zipentry indicates a project in a zip file (including directories and files), zipfile indicates a zip compressed file, and the zipfile class provides a way to obtain all the entries in the file, through these methods, we can obtain the first zipentry, which contains the information we need. You can extract it from the compressed file and write it to the local disk through the read/write stream operation, after the operation is completed, the zip file is decompressed.

Zipinputstream indicates the input stream of the ZIP file. This class can also be used to decompress the file. There is also a way to obtain zipentry. Similarly, zipfile can be decompressed through stream read/write.

Zipoutputstream indicates the output stream of the ZIP file, which can be compressed by zip. It also adds the newly created zipentry (directory or file) to the output stream through relevant methods, then, write the local disk file into the zip compressed file through stream reading and writing (if it is a directory, no stream operation is required, just add zipentry to the output stream), and finally output it to the disk.

There is a problem in the decompression process. It should be noted that the compressed file contains directory nesting. In fact, there is a method isdirectory () in zipentry, but I tried it, regardless of the situation, this method returns false. I don't know if I have something wrong, so I want to create a directory in a stupid way: if the current zipentry name (which can be obtained through getname () is file. the end of the separator indicates that the entry is a directory and is created. If not, it is extracted. If anyone has a good method, please kindly advise.

I don't know much about it, and my personal understanding is not very thorough. The following is a simple example. It is just the use of several APIs, but it is still simple to compress and decompress, if you are paying attention to it, we hope it will be helpful.

Decompress the zip package that comes with JDK to zip the file:

Package com.ninemax.demo.zip; import Java. io. file; import Java. io. ioexception; import Java. io. inputstream; import Java. io. outputstream; import Java. util. enumeration; import java.util.zip. zipentry; import java.util.zip. zipfile; import java.util.zip. zipinputstream; import java.util.zip. zipoutputstream; import Org. apache. commons. io. fileutils; import Org. apache. commons. io. ioutils;/*** compress the specified file or directory * decompress the specified compressed file (only for Zi P format ). * JDK, does not rely on other open-source projects * @ author zyh */public class ziputil {/*** to compress all files in the specified file or directory and generate compressed files in the specified path. * If the path or parent path of the compressed file does not exist, it is automatically created. * @ Param srcfile the file or directory to be compressed * @ Param destffile the path of the final compressed file generated * @ throws ioexception */public static void zipfile (string srcfile, string destfile) throws ioexception {zipfile (new file (srcfile), new file (destfile ));} /*** compress all files in a specified file or directory and generate a compressed file in the specified path. * If the path or parent path of the compressed file does not exist, Will be automatically created. * @ Param srcfile the file or directory to be compressed * @ Param destfile: Path of the final compressed file generated * @ throws ioexception */public static void zipfile (File srcfile, file destfile) throws ioexception {zipfile (srcfile, fileutils. openoutputstream (destfile);}/*** compresses all files in the specified file or directory and writes the stream to the specified output stream. ** @ Param srcfile the directory to be compressed * @ Param outputstream is used to receive the output stream of the compressed file stream */Private Static void zipfile (File srcfile, outputstream ){ Zipfile (srcfile, new zipoutputstream (outputstream);}/*** compresses all files in the specified directory and writes the stream to the specified zip output stream. ** @ Param srcfile: directory to be compressed * @ Param zipout: Zip output stream for receiving compressed file streams */Private Static void zipfile (File srcfile, zipoutputstream zipout) {try {dozipfile (srcfile, zipout, "") ;}catch (ioexception e) {e. printstacktrace ();} finally {ioutils. closequietly (zipout) ;}}/*** compress the file or directory to the specified zipoutputstream * @ Param srcfile specified file or Directory * @ Param zipout specifies the zipoutputstream output stream * @ Param NS path when the file is organized to the ZIP file * @ throws ioexception */Private Static void dozipfile (File srcfile, zipoutputstream zipout, string NS) throws ioexception {If (srcfile. isfile () {zipout. putnextentry (New zipentry (NS + srcfile. getname (); inputstream is = fileutils. openinputstream (srcfile); try {ioutils. copy (is, zipout);} catch (exception e) {e. printstacktrace ();} fi Nally {ioutils. closequietly (is);} return;} For (File file: srcfile. listfiles () {string entryname = NS + file. getname (); If (file. isdirectory () {entryname + = file. separator; zipout. putnextentry (New zipentry (entryname);} dozipfile (file, zipout, entryname) ;}/ *** decompress the specified compressed file to the specified target directory. * If the specified target directory does not exist or its parent path does not exist, it is automatically created. ** @ Param zipfile: the compressed file to be decompressed * @ Param destfile: the directory of the decompressed operation */public static void unzipfile (String zipfile, string destfile) throws ioexception {unzipfile (new file (zipfile), new file (destfile ));} /*** decompress the specified compressed file to the specified target directory. * If the specified target directory does not exist or its parent path does not exist, it is automatically created. ** @ Param zipfile: the compressed file to be decompressed * @ Param destfile: directory of the decompression operation */public static void unzipfile (File zipfile, file destfile) throws ioexception {unzipfile (fileutils. openinputstream (zipfile), destfile); // dounzipfile (New zipfile (zipfile), destfile) ;} Public static void dounzipfile (zipfile, file DEST) throws ioexception {If (! DeST. exists () {fileutils. forcemkdir (DEST);} enumeration <zipentry> entries = (enumeration <zipentry>) zipfile. entries (); While (entries. hasmoreelements () {zipentry entry = entries. nextelement (); file = new file (DEST, entry. getname (); If (entry. getname (). endswith (file. separator) {fileutils. forcemkdir (File);} else {outputstream out = fileutils. openoutputstream (File); inputstream in = zipfile. getindium Utstream (entry); try {ioutils. copy (In, out);} catch (exception e) {e. printstacktrace ();} finally {ioutils. closequietly (out) ;}} zipfile. close ();}/*** extract the specified input stream to the specified target directory. ** @ Param is the input stream to be decompressed * @ Param destfile the destination directory for the decompression operation * @ throws ioexception */public static void unzipfile (inputstream is, file destfile) throws ioexception {try {If (is instanceof zipinputstream) {dounzipfile (zipinputstream) is, des Tfile);} else {dounzipfile (New zipinputstream (is), destfile);} catch (ioexception e) {e. printstacktrace ();} finally {ioutils. closequietly (is) ;}}/***** @ Param zipinput * @ Param DEST * @ throws ioexception */Private Static void dounzipfile (zipinputstream zipinput, file DEST) throws ioexception {If (! DeST. exists () {fileutils. forcemkdir (DEST);} For (zipentry entry; (Entry = zipinput. getnextentry ())! = NULL;) {string entryname = entry. getname (); file = new file (DEST, entry. getname (); If (entryname. endswith (file. separator) {fileutils. forcemkdir (File);} else {outputstream out = fileutils. openoutputstream (File); try {ioutils. copy (zipinput, out);} catch (exception e) {e. printstacktrace ();} finally {ioutils. closequietly (out) ;}} zipinput. closeentry () ;}/// test public static void main (string [] ARGs) {try {// zipfile ("M: \ zip \ test \ tempzip ", "m: \ zip \ test \ bbc.zip"); unzipfile ("M: \ zip \ test \ bbc.zip", "m: \ zip \ test \ BB \ ");} catch (ioexception e) {e. printstacktrace ();}}}

Note: 1. For details, refer to the JDK documentation.

2. JDK's own zip package does not support Chinese characters. Therefore, there are many solutions on the Internet to introduce Apache. This is not described here, and the article is too long to stink, write another article.

3. Password is not supported. There are other projects that support password on the Internet. If possible, let's introduce them in another article!

For Java operations on ZIP files with passwords, see:

Http://blog.csdn.net/zhangyihui1986/article/details/7724229

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.