Java File compression and decompression (3)

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. zipOutputStream; // error Summary: // 1 about file. isFile () and file. isDirectory () memory deviation. // The error indicates that if Directory must be file, file is not necessarily Directory // correct: file and Directory are two different tasks. only f One of. // The value 1 indicates that a path is compressed directly. // 2 does not mean that we execute a statement File f = new File ("F: \ x.txt"); // an x.txt File is generated on the primary hard disk. the following operations must be performed. // File f = new File ("F: \ x.txt"); // if (! F. exists () {// f. createNewFile (); //} // Where f. createNewFile () indicates that an empty File is created. // in most cases, File f = new File ("F: \ x.txt") is executed ") // use the input stream to reuse the output stream to operate the stream. For example, use the following example: // write hello world /// 3 to the x.txt file: // 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 (). // extract each zipEntry. // see the decompressed code: // new File (unzipPath + File. separator + entry. getName (); public class TestZipAndUnZip {public static void main (Stri Ng [] args) throws Exception {TestZipAndUnZip test = new TestZipAndUnZip (); // compress a file into zip // test.zip ("E :\\", "aa \ 1.txt"," E: \ cc1.zip "); // compress a directory into a zip file // test.zip (" E: \ aa ", "bb \", "E: \ zz.zip"); // right // test.zip ("F: \", "kk", "F: \ zz678910.zip "); // right // extract a zip file // test. unZipFile ("F :\\ zz678910.zip", "E :\\ zzzz "); /// // The following is correct ///////////////// ///////////// compression and decompression of a single file test. z Ip2 ("F :\\ kk \ cc.txt", "F :\\ 88.zip"); test. unZipFile2 ("F :\\ 88.zip"," F :\\ abc "); // compress and decompress a directory test.zip 2 (" F: \ kk "," F: \ 9zip.zip "); test. unZipFile2 ("F: \ 9zip.zip", "F: \ 9 files "); ///////////////// /// //}/*** @ 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 willZipFil EName, String 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 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 zipEntry = new ZipEntry (getEntryName (dirPath, WillZipDir); System. out. println ("xxxxxxxxxxxxxxxx" + zipEntry. getName (); 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 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");} // if it is a file, recursively call 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. decompress the package to make it public String g. EtEntryName (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 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 () {// The code System. out. println ("999999999999"); new File (unzipedFileName ). mkdirs ();} else {// always execute this code. because each file is compressed during compression. new File (unzipedFileName ). getParentFile (). mkdirs ();} FileOutputStream fos = null; InputStream is = null; File unzipedFile = new File (unzipedFileName); if (unzipedFile. isDirectory () {File [] files = unzipedFile. listFiles (); for (int I = 0; I <files. length; I ++) {F Ile file = files [I]; fos = new FileOutputStream (file); is = zipedFile. getInputStream (zipEntry); while (len = is. read (buffer ))! =-1) {fos. write (buffer, 0, len) ;}} else {fos = new FileOutputStream (unzipedFile); is = zipedFile. getInputStream (zipEntry); while (len = is. read (buffer ))! =-1) {fos. write (buffer, 0, len) ;}// here you need to modify // 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 willZipFile = new File (willZipPath); File zipedFile = New File (zipedPath); ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (zipedFile); if (willZipFile. isFile () {fileToZip2 (willZipPath, zos);} if (willZipFile. isDirectory () {dirToZip2 (willZipPath, willZipFile, zos);} // close the stream zos after the method is called. close ();} catch (Exception e) {// TODO: handle exception}/*** @ param willZipFilePath path of the file to be compressed * @ param zos compressed file output stream * 1 the following two statements about Code * ZipEntry entry = new Zip Entry (); * zos. putNextEntry (entry); * Add the generated ZipEntry object to the compressed file * and then write the content to the compressed file to the ZipEntry object. close () but cannot zos here. close () * because the zos is passed in the previous method. the zos stream may be used again when the directory is compressed. if this is disabled, a File in the directory * is compressed */public void fileToZip2 (String willZipFilePath, ZipOutputStream zos) {try {File willZipFile = new File (willZipFilePath ); zipEntry entry = new ZipEntry (getEntryName2 (willZipFilePath, willZipFile); zos. putNextE Ntry (entry); FileInputStream FCM = new FileInputStream (willZipFilePath); int len = 0; while (len = Fi. read ())! =-1) {zos. write (len);} FCM. close (); // stream close error! // Zos. close ();} catch (Exception e) {}}/*** @ param willZipDirctoryPath: Path of the original directory * @ param willZipedDirectory original directory * @ param zos compressed stream * Note: * when processing empty folders * getEntryName2 (willZipDirctoryPath, willZipedDirectory) + "/" * "/" is not less than */public void dirToZip2 (String willZipDirctoryPath, File willZipedDirectory, zipOutputStream zos) {if (willZipedDirectory. isDirectory () {File [] files = willZipedDirectory. listFil Es (); // process empty folders if (files. length = 0) {ZipEntry zipEntry = new ZipEntry (getEntryName2 (willZipDirctoryPath, willZipedDirectory) + "/"); try {zos. putNextEntry (zipEntry);} catch (Exception e) {e. printStackTrace () ;}return ;}for (int I = 0; I <files. length; I ++) {File file = files [I]; // recursively call fileToZip () if (file. isFile () {fileToZip2 (file. getAbsolutePath (), zos);} // recursively call dirToZip () if (file. isDirectory () {DirToZip2 (file. getAbsolutePath (), file, zos );}}}} /*** @ param rawPath refers to the directory or full path of the file to be compressed * @ param file refers to the file or directory to be compressed * @ return entryName ** this method returns EntryName, indicates the complete path from the outermost directory to the file (directory) * remarks: * 1 all files in this example are stored in a disk, such as E: \ so rawPath. substring (3); * 2 comment on "@ param file files or directories to be compressed ". in most cases, * files are used, and only directories are empty folders. */public String getEntryName2 (String rawPath, File file) {try {String rawDir = 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 decompressed file * Small sorting of file or directory operations: * 1 file the directory first. mkdir (s) () can * store files under it. for example, * File f = new File ("F: \ test \ x.txt"); if (! F. exists () f.createnewfile({{}}this is certainly an error because the directory of x.txt does not exist !! Therefore, it should be corrected to: File f = new File ("F: \ test \ x.txt"); f. getParentFile (). mkdirs (); if (! F. exists () {f. createNewFile ();} 2 Similarly, File f = new File ("F: \ test \ x.txt"); if (f. isFile () {System. out. println ("true");} else {System. out. println ("false");} the result is a problem similar to false3: File f = new File ("F: \ x.txt"); if (f. isFile () {System. out. println ("true");} else {System. out. println ("false");} The result is false because only a new File is created and not created !!! File f = new File ("F: \ x.txt"); f. createNewFile (); if (f. isFile () {System. out. println ("true");} else {System. out. println ("false");} is true here: if (zipEntry. isDirectory () {new File (perUnzipFilePath ). mkdirs ();} else {new File (perUnzipFilePath ). getParentFile (). mkdirs ();} has created each folder. then start streaming for each empty folder and each file. consistent with the above principle, I made a mistake at the beginning and did not use else {fos = new FileOutputStream (perUnzipFile); is = zipFile. getInputStream (zipEntr Y); while (len = is. read (buffer ))! =-1) {fos. write (buffer, 0, len) ;}} uses if (perUnzipFile. isFile () {}. Of course this is wrong. because this perUnzipFile does not execute perUnzipFile. createNewFile (); so it is not File. in a similar case, stream operations are mostly used for reading and writing. therefore, two operations related to File are summarized: 1 File f = new File (""); f. createNewFile (); then operate f 2 file f = new File (""); then use the input/output stream for stream operations. For example: File f = new File ("F: \ 2221x.txt "); FileOutputStream fos = new FileOutputStream (f); String string =" hello "; byte [] B = string. getBytes (); fos. write (B, 0, B. length); this example is correct. question: f. createNewFile () does not report an error. because the output stream FileOutputStream has already helped us do this. the modification example shows: File f = new File ("F: \ 2221x.txt"); if (f. isFile () {System. out. println ("true1");} else {System. out. println ("false1");} FileOutputStream fos = new FileOutputStream (f); if (f. isFile () {System. out. println ("true2");} else {System. out. println ("false2");} String string = "hello"; byte [] B = string. getBytes (); fos. writ E (B, 0, B. length); the output false1 and true2 are verified. */public void unZipFile2 (String zipedFilePath, String unzipPath) {FileOutputStream fos = null; InputStream is = null; ZipEntry zipEntry = null; String perUnzipFilePath = null; if (! UnzipPath. endsWith (File. separator) {unzipPath + = File. separator;} try {ZipFile zipFile = new ZipFile (zipedFilePath); Enumeration entries = zipFile. entries (); byte [] buffer = new byte [1024*8]; int len = 0; while (entries. hasMoreElements () {zipEntry = (ZipEntry) entries. nextElement (); perUnzipFilePath = unzipPath + zipEntry. getName (); // 1 create each folder if (zipEntry. isDirectory () {// process empty folders // create an empty directory new File (perUnzipFilePa Th ). mkdirs ();} else {// create its directory for each File new File (perUnzipFilePath ). getParentFile (). mkdirs ();} // 2. The operations in stream operations to process files in each folder // 2.1if are only performed for empty directories. therefore, the code in if can be commented out // without practical significance. // The operation in 2.2else is the stream operation File perUnzipFile = new File (perUnzipFilePath) for each specific File; if (perUnzipFile. isDirectory () {File [] files = perUnzipFile. listFiles (); for (int I = 0; I <files. length; I ++) {File file = files [I]; fos = new FileOutputStream (file ); Is = zipFile. getInputStream (zipEntry); while (len = is. read (buffer ))! =-1) {fos. write (buffer, 0, len) ;}} else {fos = new FileOutputStream (perUnzipFile); is = zipFile. getInputStream (zipEntry); while (len = is. read (buffer ))! =-1) {fos. write (buffer, 0, len) ;}} if (fos! = Null) {fos. close () ;}if (is! = Null) {is. close () ;}} catch (Exception e) {e. printStackTrace ();}}}

 

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.