Friday, November 22, 2019

How To Practise A Zilch File Inward Java? Zipentry Together With Zipoutputstream Compression Example

Since compressing together with archiving erstwhile log file is an essential housekeeping task inwards whatever Java application environment, a Java programmer should know how to compress files inwards .zip format together with thus how to read them programmatically if required. The JDK provides total back upward to practice together with read ZIP files inwards Java. There is a split parcel java.util.zip to concord all classes related zipping together with unzipping files together with streams. In this serial of article, y'all volition larn how to usage those classes e.g. ZipFile, ZipEntry, ZipInputStream, together with ZipOutputStream etc. This is the mo article almost how to piece of occupation amongst compressed archives inwards Java e.g. .zip files. In the final article, I induce got shown y'all how to read ZIP archives inwards Java together with today, I'll learn y'all 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 practice a .zip file past times using JDK's ZIP file back upward classes.

You practice a .zip file inwards Java to archive files together with directory inwards the compressed format. The JDK (Java Development Kit) provides necessary classes to brand a nix file inwards java.util.zip package. You instance usage ZipEntry, ZipFile, together with ZipOutputStream classes to compress files together with practice a nix archive. But earlier that, let's unopen to of import classes together with their functions.

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

Btw, the java.util.zip parcel non alone provides classes to read together with write files compressed inwards ZIP format, but also classes to read/write GZIP format classes every bit good e.g. GZIPInputStream together with GZIPOutputStream. We'll larn almost them inwards unopen to upcoming tutorials. If y'all are curious almost them but at i time thus reading Core Java For The Impatient past times Cay S. Horstmann.


Unlike at that topographic point were two ways to read ZIP file inwards Java e.g. past times using ZipInputStream together with ZipFile, at that topographic point is alone i means to practice Zip file inwards Java i.e. past times using ZipOutputStream. This degree writes information to an output current inwards the ZIP file format. If y'all desire to shop information inwards a file, y'all must chain ZipOutputStream to a FileOutputStream, similar to what nosotros practice inwards Decorator pattern.

Once y'all practice the nix output stream, the adjacent mensuration volition hold out to opened upward rootage text files which y'all desire to compress. You induce got to practice a nix entry for each file using the java.util.zip.ZipEntry degree together with earlier y'all write the information to stream, y'all must outset pose the nix entry object using the putNextEntry() method of ZipOutputStream. Once this is done, y'all tin write the information together with unopen the stream.

So, these were the 3 steps y'all demand to follow to compress a text file together with practice a ZIP file inwards Java i.e.
  1. Create a FileOutputStream to practice nix file
  2. Pass that FileOutputStream to ZipOutputStream to write information inwards zipping file format. 
  3. Optionally y'all tin wrap FileOutputStream into BufferedOutputStream for ameliorate write performance.
  4. Open each rootage 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 representative of creating a nix 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 programme to parcel files inwards a ZIP file inwards Java. In this program, nosotros induce got a brace of text files together with a directory amongst a file inwards the Eclipse projection directory. We'll compress those files together with directory to practice a compressed file inwards ZIP file format. You tin usage 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 nix tool e.g. Winzip, WinRAR, or 7Zip etc.

Anyway, hither is the hide shot of the files together with directory which volition hold out compressed to practice a ZIP file inwards Java:
 Since compressing together with archiving erstwhile log file is an essential housekeeping task inwards whatever Java How to practice a ZIP File inwards Java? ZipEntry together with ZipOutputStream Compression Example

The files which volition hold out compressed are names.txt, java7.txt, together with java.txt. I'll also include the directory targetrr, which contains an apache.txt file, but to demonstrate that y'all tin also include subdirectories amongst files field zipping them.  Unfortunately, these files are non large thus y'all won't meet the final result of compression e.g. compressing a 1GB text file to practice a ZIP file inwards KB, but y'all tin practice that yourself. Just re-create the log file y'all desire to compress inwards the archive directory together with run the program.


Java Program to practice 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 practice 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 practice 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 nix 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 nix file Writing file : 'java7.txt' to nix file Writing file : 'targetrr/apache.txt' to nix file Writing file : 'java.txt' to nix file


If y'all opened upward this ZIP file inwards your car using WinZIP or WinRAR y'all tin meet that it contains all 3 files together with the unmarried directory amongst a file nosotros induce got but added, every bit shown below:

 Since compressing together with archiving erstwhile log file is an essential housekeeping task inwards whatever Java How to practice a ZIP File inwards Java? ZipEntry together with ZipOutputStream Compression Example


Important Points

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

1) Compression together with archiving are ii dissimilar things, but inwards Windows tools, similar Winzip does both i.e. they compress the files together with archive them into a split file.

2) In UNIX, y'all induce got to usage split commands for archiving together with compression e.g. tar command is used for archiving together with 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 together with GZIP file formats, It provides classes to read, practice together with alter ZIP together with GZIP file formats. For example,  you tin usage ZipInputStream /ZipOutputStream to read/write ZIP file format together with GZIPInputStream together with GZIPOutputStream to read/write compressed information inwards GZIP file format.


That's all almost how to practice a nix file inwards Java. It's similar to creating a nix file inwards windows past times using the Winzip tool. You tin usage this programme to archive erstwhile log files to salvage unopen to infinite on your Web Server. You tin also lift this programme to induce got the input together with output place i.e. the place to selection files together with where to practice the output files. You tin read to a greater extent than almost compression together with archive inwards Java on Java: How to Program past times Deitel together with Deitel, i of the most consummate books inwards Java, which covers almost everything from inwardness Java to Swing to JDBC.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

No comments:

Post a Comment