Java File compression and decompression (4)

Source: Internet
Author: User
Package com.cn; import Java. io. file; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstream; import Java. util. enumeration; import java.util.zip. zipentry; import java.util.zip. zipfile; import java.util.zip. zipinputstream; import java.util.zip. zipoutputstream; // error Summary: // 1 about file. isfile () and file. isdirectory () memory deviation. // The error indicates that if directory must be file, the file is not necessarily di. Rectory // correct: file and directory are two different things. it can only be one of file or directory. // The value 1 indicates that a path is compressed directly. // 2 blood lessons: // the ZOS stream is not disabled in the ZIP () method. an error occurred while extracting the compressed file. // Important Note: // 1. The core operation object for zip and unzip is every file !!! // For example, if you encounter a directory, it will traverse every file and compress it one by one. // do not mistakenly understand that a directory is compressed as a whole. // 2 in Java, each compressed file is represented by a zipentry. // You must obtain the complete path of each file during the compression process (from the outermost folder to the file itself) // use this full path to create a zipentry for each compressed file new () // 3 so zipentry can be used to record the original directory hierarchy. decompress the package to keep it as it is. // you can also see that entrys is used during decompression. hasmoreelements () to decompress each zipentrypublic class testzipandunzip {public static void main (string [] ARGs) throws exception {testzipandunzip test = new testzipandun Zip (); // compress a file to zip // test.zip ("E: \", "AA \ 1.txt"," E: \ cc1.zip "); // compress a directory into zip // test.zip ("E: \ AA", "BB \", "E: \ zz.zip "); // right /// test.zip ("E: \", "AA", "E: \ zz678910.zip "); // right // extract a zip file // test. unzipfile ("E: \ zz.zip", "E: \ ZZZZ "); /// // The following is correct ///////////////// ///////////// compress and decompress a single file // test.zip 2 ("E: \ AA \ 1.txt", "E: \ aaaaaaa \ aa1234.zip"); // test. unzipfile2 ("E :\\ Aaaaaaa \ aa1234.zip "," e :\\ aaaaaaa \ aaxixihaha "); // compress and decompress a directory test.zip 2 (" d :\\ developmenttools "," E: \ unzip zip"); test. unzipfile2 ("e :\\ unzip zip"," e :\\ 555aaxx99xxx "); ///////////////// /// //}/*** @ Param willzipdirpath compressed file (directory) directory * @ Param willzipfilename name of the compressed file (directory) * @ Param tofilepath name of the compressed file (directory) */Public void zip (string willzipdirpath, string willzipfilename, strin G zipedfilename) {system. Out. println ("..................... The following is the ZIP () method .............................. "); If (willzipdirpath = NULL) {return;} file willzipdir = new file (willzipdirpath); If (! Willzipdir. exists () |! Willzipdir. isdirectory () {return;} // obtain the absolute directory path string willzipdirabsolutepath = willzipdir. getabsolutepath (); system. out. println ("willzipdir. getabsolutepath () = "+ willzipdirabsolutepath); // compressed file zipedfile = new file (zipedfilename ); try {// obtain the compressed output stream from the compressed file zipoutputstream // here ZOS only points to the outermost layer of the compressed file. so how does it // maintain the original directory structure? // Zipentry is used !!! // You can see the use of zipentry in the filetozip () method !! Zipoutputstream ZOS = new zipoutputstream (New fileoutputstream (zipedfile); If (willzipfilename. equals ("*") {// If the input is *, it indicates that everything in this path must be compressed. // call dirtozip () dirtozip (willzipdirabsolutepath, willzipdir, ZOS);} else {// file willzipfile = new file (willzipdirpath, willzipfilename) to be compressed; system. out. println ("ccccccccccc name =" + willzipfile. getname (); system. out. println ("ccccccccccc getabsolutepath =" + willzipfile. g Etabsolutepath (); If (willzipfile. isfile () {system. Out. println ("..................... The outermost layer starts to compress files ........................... "); Filetozip (willzipdirpath, willzipfile, ZOS); system. Out. println ("..................... End of the outermost compressed file ........................... ");} If (willzipfile. isdirectory () {system. Out. println ("..................... The outermost layer begins to compress the directory ........................... "); Dirtozip (willzipdirpath, willzipfile, ZOS); system. Out. println ("..................... The end of the outermost compressed directory ........................... ");} // Close the stream !!! ZOS. Close (); system. Out. println ("..................... The above is the ZIP () method .............................. ") ;}} Catch (exception e) {// todo: handle exception}/*** @ Param dirpath directory of the compressed file * @ Param willzipfile name of the compressed file * @ Param ZOS output stream */Public void filetozip (string dirpath, file willzipfile, zipoutputstream ZOS) {fileinputstream FCM = NULL; zipentry = NULL; byte [] buffer = new byte [1024*8]; int Len = 0; If (willzipfile. isfile () {try {FS = new fileinputstream (willzipfile); zipentry = new zipentry (Gete Ntryname (dirpath, willzipfile); ZOS. putnextentry (zipentry); system. Out. println ("..................... The following is the filetozip () method .............................. "); System. out. println ("zipentry. getname = "+ zipentry. getname (); system. out. println ("zipentry. isdirectory = "+ zipentry. isdirectory (); system. out. println ("zipentry. getsize = "+ zipentry. getsize (); system. out. println ("zipentry. gettime = "+ zipentry. gettime (); system. out. println ("zipentry. getcomment = "+ zipentry. getcomment (); system. out. println ("..................... The above is the filetozip () method .............................. "); While (LEN = Fi. Read (buffer ))! =-1) {ZOS. write (buffer, 0, Len);} ZOS. closeentry (); FCM. close ();} catch (exception E) {}}/ *** @ Param dirpath the parent directory where the directory to be compressed is located * @ Param willzipdir compressed directory * @ Param ZOS output stream */Public void dirtozip (string dirpath, file willzipdir, zipoutputstream ZOS) {If (willzipdir. isdirectory () {file [] files = willzipdir. listfiles (); // process --> no file in this folder if (files. length = 0) {zipentry = new zipentry (getentryname (dirpath, Willzipdir); try {ZOS. putnextentry (zipentry); ZOS. closeentry ();} catch (exception e) {e. printstacktrace ();} return;} // process --> all files in this folder for (INT I = 0; I <files. length; I ++) {file = files [I]; // recursively call filetozip () if (file. isfile () {system. out. println ("xxxxxxxxxx starts the filetozip () method xxxxxxxxxx"); filetozip (dirpath, file, ZOS); system. out. println ("xxxxxxxxxx internal filetozip () method ends xxxxxxxxxx");} // recursively calls Dirtozip () if (file. isdirectory () {system. out. println ("xxxxxxxxxx"); dirtozip (dirpath, file, ZOS); system. out. println ("xxxxxxxxxx inner dirtozip () method ends xxxxxxxxxx ");}}}} /*** @ Param dirpath: directory where the compressed file is located * @ Param willzipfile: the compressed file * @ return * // generates the complete path of each file (from the outermost layer folder to the file itself) // The generated zipentry records the original directory hierarchy. after decompression, the Public String getentryname (string dirpath, file willzipfile) {If (! Dirpath. endswith (file. separator) {dirpath + = file. separator;} string willzipfilepath = willzipfile. getabsolutepath (); If (willzipfile. isdirectory () {willzipfilepath + = "/";} int Index = willzipfilepath. indexof (dirpath); system. out. println ("XX returned entryname =" + willzipfilepath. substring (index + dirpath. length (); Return willzipfilepath. substring (index + dirpath. length ();}/*** @ Param zipedfilename: zip file to be decompressed * @ Pa The outermost file name * @ throws ioexception */Public void unzipfile (string zipedfilename, string unzipdirpath) throws exception {If (! Unzipdirpath. endswith (file. separator) {unzipdirpath + = file. separator;} Try {zipfile zipedfile = new zipfile (zipedfilename); zipentry = NULL; string entryname = NULL; string unzipedfilename = NULL; enumeration entrys = zipedfile. entries (); byte [] buffer = new byte [1024*8]; int Len = 0; while (entrys. hasmoreelements () {zipentry = (zipentry) entrys. nextelement (); entryname = zipentry. getname (); unzipedfilename = unzipdi Rpath + entryname; system. Out. println ("..................... The following is the unzipfile () method .............................. "); System. out. println ("zipedfilename =" + zipedfilename); system. out. println ("unzipdirpath =" + unzipdirpath); system. out. println ("entryname =" + entryname); system. out. println ("unzipedfilename =" + unzipedfilename); system. out. println ("..................... The above is the unzipfile () method .............................. "); If (zipentry. isdirectory () {// no execution of this Code new file (unzipedfilename ). mkdirs ();} else {// always execute this code. because each file is compressed during compression. new file (unzipedfilename ). getparentfile (). mkdirs ();} file unzipedfile = new file (unzipedfilename); fileoutputstream Fos = new fileoutputstream (unzipedfile); inputstream is = zipedfile. getinputstream (zipentry); While (LEN = is. read (buffer ))! =-1) {FOS. write (buffer, 0, Len);} FOS. close (); is. close () ;}} catch (exception e) {e. printstacktrace ();}} //////////////////////////////////////// //////////////////////////////////////// /// // *** this method compresses the file in a given path * @ Param willzippath: Path of the file to be compressed * @ Param zipedpath: Path of the compressed file */ public void zip2 (string willzippath, string zipedpath) {try {file willzipedfile = new file (willzippath); file zipedfile = new file (ziped Path); zipoutputstream ZOS = new zipoutputstream (New fileoutputstream (zipedfile); If (willzipedfile. isfile () {filetozip2 (willzippath, willzipedfile, ZOS);} If (willzipedfile. isdirectory () {dirtozip2 (willzippath, willzipedfile, ZOS);} // close the stream ZOS after the method is called. close ();} catch (exception e) {// todo: handle exception}/*** @ Param rawpath * @ Param willzipedfile * @ Param ZOS * // test.zip 2 ("E: \ AA \ 1.txt"," E: \ AAAA AAA \ aa1234.zip "); Public void filetozip2 (string rawpath, file willzipedfile, zipoutputstream ZOS) {try {// compile a zipentry object named AB .txt file = new file (rawpath ); zipentry entry = new zipentry (getentryname2 (rawpath, file )); // Add the generated zipentry object to the compressed file // The content written to the compressed file will be placed in the zipentry object ZOS. putnextentry (entry); inputstream is = new fileinputstream (rawpath); int Len = 0; while (LEN = is. read ())! =-1) {ZOS. Write (LEN);} is. Close (); // stream close Error !! // ZOS. close ();} catch (exception E) {}}/*** @ Param rawpath: Path of the original file * @ Param zipedfile: compressed file * @ Param ZOS */Public void dirtozip2 (string rawpath, file zipedfile, zipoutputstream ZOS) {If (zipedfile. isdirectory () {file [] files = zipedfile. listfiles (); // process --> no file in this folder // If (files. length = 0) {// zipentry = new zipentry (getentryname (dirpath, willzipdir); // zipentry = new zipentry (""); // t Ry {// ZOS. putnextentry (zipentry); // ZOS. closeentry (); //} catch (exception e) {// E. printstacktrace (); //} // return; //} For (INT I = 0; I <files. length; I ++) {file = files [I]; // recursively call filetozip () if (file. isfile () {filetozip2 (file. getabsolutepath (), file, ZOS);} // recursively call dirtozip () if (file. isdirectory () {dirtozip2 (file. getabsolutepath (), file, ZOS) ;}}}/*** @ Param rawpath indicates the full path of the directory or file to be compressed * @ P Aram file: the file to be compressed * @ return entryname */Public String getentryname2 (string rawpath, file) {// file is the filetry {string rawdir = rawpath corresponding to rawpath. substring (3); int rawdirindex = file. getabsolutepath (). indexof (rawdir); string entryname = file. getabsolutepath (). substring (rawdirindex); Return entryname;} catch (exception e) {} return NULL ;} /*** @ Param zipedfilepath: Path of the original compressed file * @ Param unzippath: path of the unzipped file */Public Void unzipfile2 (string zipedfilepath, string unzippath) {try {// decompressed outermost folder file unzipfile = new file (unzippath); If (! Unzipfile. exists () {unzipfile. mkdirs ();} file zipedfile = new file (zipedfilepath); file perunzipedfile = NULL; // It is easy to get the zipfile object instantiated !!!! // Zipfile = new zipfile (File); zipinputstream zis = new zipinputstream (New fileinputstream (zipedfile); fileoutputstream Fos = NULL; zipentry entry = NULL; while (Entry = Zis. getnextentry ())! = NULL) {// get a compressed object perunzipedfile = new file (unzippath + file. Separator + entry. getname (); If (! Perunzipedfile. getparentfile (). exists () {perunzipedfile. getparentfile (). mkdirs (); // create parent directory} If (! Perunzipedfile. exists () {// determine whether the output file contains perunzipedfile. createnewfile (); // create a file} // obtain the input stream Fos = new fileoutputstream (perunzipedfile) for each object; int Len = 0; while (LEN = Zis. read ())! =-1) {FOS. write (LEN) ;}} Zis. close (); FOS. close () ;}catch (exception e) {// todo: handle exception }}}

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.