How to occupation a ZIP File inwards Java? ZipEntry in addition to ZipOutputStream Compression Example

Since compressing as well as archiving quondam log file is an essential housekeeping task inwards whatever Java application environment, a Java programmer should know how to compress files inwards .zip format as well as and hence how to read them programmatically if required. The JDK provides total back upward to practise as well as read ZIP files inwards Java. There is a dissever bundle java.util.zip to concur all classes related zipping as well as unzipping files as well as streams. In this serial of article, yous volition larn how to utilisation those classes e.g. ZipFile, ZipEntry, ZipInputStream, as well as ZipOutputStream etc. This is the minute article almost how to piece of occupation amongst compressed archives inwards Java e.g. .zip files. In the final article, I stimulate got shown yous how to read ZIP archives inwards Java as well as today, I'll instruct yous how to compress files inwards the ZIP file format past times yourself using a Java program. You volition compress a bunch of text file to practise a .zip file past times using JDK's ZIP file back upward classes.

You practise a .zip file inwards Java to archive files as well as directory inwards the compressed format. The JDK (Java Development Kit) provides necessary classes to brand a nil file inwards java.util.zip package. You instance utilisation ZipEntry, ZipFile, as well as ZipOutputStream classes to compress files as well as practise a nil archive. But earlier that, let's but about of import classes as well as their functions.

  • java.util.zip.ZipFile - This shape is used to read entries from a nil file. 
  • java.util.zip.ZipEntry - This shape is used to stand upward for a ZIP file entry.
  • java.util.zip.ZipInputStream - This shape implements an input current filter for reading files inwards the ZIP file format. Includes back upward for both compressed as well as uncompressed entries.
  • java.util.zip.ZipOutPutStream - This shape implements an output current filter for writing files inwards the ZIP file format. Includes back upward for both compressed as well as uncompressed entries.

Btw, the java.util.zip bundle non exclusively provides classes to read as well as write files compressed inwards ZIP format, but also classes to read/write GZIP format classes every bit good e.g. GZIPInputStream as well as GZIPOutputStream. We'll larn almost them inwards but about upcoming tutorials. If yous are curious almost them but straightaway as well as hence reading Core Java For The Impatient past times Cay S. Horstmann.


Unlike in that place were two ways to read ZIP file inwards Java e.g. past times using ZipInputStream as well as ZipFile, in that place is exclusively 1 agency to practise Zip file inwards Java i.e. past times using ZipOutputStream. This shape writes information to an output current inwards the ZIP file format. If yous desire to shop information inwards a file, yous must chain ZipOutputStream to a FileOutputStream, similar to what nosotros practise inwards Decorator pattern.

Once yous practise the nil output stream, the adjacent mensuration volition hold upward to opened upward root text files which yous desire to compress. You stimulate got to practise a nil entry for each file using the java.util.zip.ZipEntry shape as well as earlier yous write the information to stream, yous must start seat the nil entry object using the putNextEntry() method of ZipOutputStream. Once this is done, yous tin write the information as well as unopen the stream.

So, these were the 3 steps yous demand to follow to compress a text file as well as practise a ZIP file inwards Java i.e.
  1. Create a FileOutputStream to practise nil file
  2. Pass that FileOutputStream to ZipOutputStream to write information inwards zipping file format. 
  3. Optionally yous tin wrap FileOutputStream into BufferedOutputStream for improve write performance.
  4. Open each root file using File class
  5. Create a ZipEntry past times using those File objects
  6. Put the ZipEntry into ZipOutputStream using putNextEntry() method
  7. write the information to the ZIP file using write() method of ZipOutputStream.
  8. close the stream

We'll meet the consummate code illustration of creating a nil file inwards Java inwards adjacent department to meet these steps inwards action.




How to Create a Zip file inwards Java Code

Here is our consummate Java plan to bundle files inwards a ZIP file inwards Java. In this program, nosotros stimulate got a pair of text files as well as a directory amongst a file inwards the Eclipse projection directory. We'll compress those files as well as directory to practise a compressed file inwards ZIP file format. You tin utilisation this file similar to the .zip file created WinZip or WinRAR utility which archives files using ZIP format. You tin fifty-fifty opened upward them using whatever nil tool e.g. Winzip, WinRAR, or 7Zip etc.

Anyway, hither is the covert shot of the files as well as directory which volition hold upward compressed to practise a ZIP file inwards Java:
 Since compressing as well as archiving quondam log file is an essential housekeeping task inwards whatever Java How to practise a ZIP File inwards Java? ZipEntry as well as ZipOutputStream Compression Example

The files which volition hold upward compressed are names.txt, java7.txt, as well as java.txt. I'll also include the directory targetrr, which contains an apache.txt file, but to demonstrate that yous tin also include subdirectories amongst files piece zipping them.  Unfortunately, these files are non large hence yous won't meet the termination of compression e.g. compressing a 1GB text file to practise a ZIP file inwards KB, but yous tin practise that yourself. Just re-create the log file yous desire to compress inwards the archive directory as well as run the program.


Java Program to practise ZIP File inwards Java
package demo;  import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;  /**  * Java Program to demonstrate how to practise ZIP file inwards Java. ZIP file contains  * private files inwards compressed format.  *   * @author java67  */  public class FileCopyDemo {      public static void main(String args[]) {          try {             // let's practise a ZIP file to write data             FileOutputStream fos = new FileOutputStream("sample.zip");             ZipOutputStream zipOS = new ZipOutputStream(fos);              String file1 = "names.txt";             String file2 = "java7.txt";             String file3 = "targetrr/apache.txt";             String file4 = "java.txt";              writeToZipFile(file1, zipOS);             writeToZipFile(file2, zipOS);             writeToZipFile(file3, zipOS);             writeToZipFile(file4, zipOS);              zipOS.close();             fos.close();          } catch (FileNotFoundException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         }      }      /**      * Add a file into Zip archive inwards Java.      *       * @param fileName      * @param zos      * @throws FileNotFoundException      * @throws IOException      */     public static void writeToZipFile(String path, ZipOutputStream zipStream)             throws FileNotFoundException, IOException {          System.out.println("Writing file : '" + path + "' to nil file");          File aFile = new File(path);         FileInputStream fis = new FileInputStream(aFile);         ZipEntry zipEntry = new ZipEntry(path);         zipStream.putNextEntry(zipEntry);          byte[] bytes = new byte[1024];         int length;         while ((length = fis.read(bytes)) >= 0) {             zipStream.write(bytes, 0, length);         }          zipStream.closeEntry();         fis.close();     } }  Ouput : Writing file : 'names.txt' to nil file Writing file : 'java7.txt' to nil file Writing file : 'targetrr/apache.txt' to nil file Writing file : 'java.txt' to nil file


If yous opened upward this ZIP file inwards your motorcar using WinZIP or WinRAR yous tin meet that it contains all 3 files as well as the unmarried directory amongst a file nosotros stimulate got but added, every bit shown below:

 Since compressing as well as archiving quondam log file is an essential housekeeping task inwards whatever Java How to practise a ZIP File inwards Java? ZipEntry as well as ZipOutputStream Compression Example


Important Points

Some useful of import points related to compression, archiving, as well as how to piece of occupation amongst compressed files e.g. ZIP as well as GZIP files inwards Java:

1) Compression as well as archiving are 2 dissimilar things, but inwards Windows tools, similar Winzip does both i.e. they compress the files as well as archive them into a dissever file.

2) In UNIX, yous stimulate got to utilisation dissever commands for archiving as well as compression e.g. tar command is used for archiving as well as gzip is used to compress the archived file.

3) Files added to a ZIP/JAR file are compressed individually

4) The JDK back upward both ZIP as well as GZIP file formats, It provides classes to read, practise as well as alter ZIP as well as GZIP file formats. For example,  you tin utilisation ZipInputStream /ZipOutputStream to read/write ZIP file format as well as GZIPInputStream as well as GZIPOutputStream to read/write compressed information inwards GZIP file format.


That's all almost how to practise a nil file inwards Java. It's similar to creating a nil file inwards windows past times using the Winzip tool. You tin utilisation this plan to archive quondam log files to relieve but about infinite on your Web Server. You tin also heighten this plan to convey the input as well as output place i.e. the place to selection files as well as where to practise the output files. You tin read to a greater extent than almost compression as well as archive inwards Java on Java: How to Program past times Deitel as well as Deitel, 1 of the most consummate books inwards Java, which covers almost everything from heart as well as soul Java to Swing to JDBC.


Subscribe to receive free email updates:

0 Response to "How to occupation a ZIP File inwards Java? ZipEntry in addition to ZipOutputStream Compression Example"

Posting Komentar