Java File compression and decompression (1)

Source: Internet
Author: User
Package com.cn; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; 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. it can only be one of file or Directory. // 2 does not mean Execute a File f = new File ("F: \ x.txt"); // an x.txt File is generated on the hard drive. 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: // perUnzipFilePath = unzipPath + zipEntry. getName (); public class TestZipAndUnZip {public static void main (Strin G [] args) throws Exception {TestZipAndUnZip test = new TestZipAndUnZip (); // compress and decompress a single file test.zip 2 ("F: \ kk \ cc.txt", "F: \ 11.zip"); test. unZipFile2 ("F :\\ 11.zip"," F :\\ test11 "); // compress and decompress a directory test.zip 2 (" F: \ kk "," F: \ 22.zip"); test. unZipFile2 ("F :\\ 22.zip"," F :\\ test22 ");} /*** this method compresses the file in a given path * @ param willZipPath path of the file to be compressed * @ param zipedPath the compressed path of the 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) {}}/*** @ param willZipFilePath path of the file to be compressed * @ param zos compressed file output stream * 1 the following two statements of code * ZipEntry entry = new ZipEntry (); * 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 (wil LZipFilePath, willZipFile); zos. putNextEntry (entry); FileInputStream FD = 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 indispensable */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 ();}}}

PS:

Java File compression and decompression (1), preferably.

Java File compression and decompression (3), followed.

 

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.