The Java.util.zip package provides classes that can process the compression and decompression of files, which inherit from the Outputsteam and InputStream of the byte stream. where Gzipoutputstream and Zipoutputstream can compress data into both GZIP and ZIP formats, Gzipinpputstream and Zipinputstream can restore compressed data.
The general steps for writing files to a compressed file are as follows: build the compressed class object associated with the compressed file that you want to generate. Compressed files usually contain more than one file, each file to be added is called a compression entry, and a compressed entry object is generated using ZipEntry (String FileName). Use Putnextentry (ZipEntry entry) to add a compressed entry to the compressed file. Writes the contents of the file to this compressed file. Use Closeentry () to end the current compression entry and continue to the next compression entry.
The general steps for reading a file from a compressed file are as follows: builds the compressed class object associated with the compressed file to be read. Use Getnextentry () to get the next compression entry.
"Example 10-13" enters several file names, compresses all files to "Ep10_13.zip", and then extracts and displays them from the compressed file.
Ep10_13.java **********
Import java.io.*;
Import java.util.*;
Import java.util.zip.*;
Class ep10_13{
public static void Main (String args[]) throws ioexception{
FileOutputStream a=new FileOutputStream ("Ep10_13.zip");
Working with compressed files
Zipoutputstream out=new Zipoutputstream (New Bufferedoutputstream (a));
for (int i=0;i<args.length;i++) {//to handle each file entered by the command line
System.out.println ("Writing file" +args[i]);
Bufferedinputstream in=new Bufferedinputstream (New FileInputStream (args[i));
Out.putnextentry (New ZipEntry (args[i)); Set the ZipEntry object
int b;
while ((B=in.read ())!=-1)
Out.write (b); Read from the source file and write to the compressed file
In.close ();
}
Out.close ();
Unzip the file and display
System.out.println ("Reading file");
FileInputStream d=new FileInputStream ("Ep10_13.zip");
Zipinputstream inout=new Zipinputstream (new Bufferedinputstream (d));
ZipEntry Z;
while ((Z=inout.getnextentry ())!=null) { //get access
SYSTEM.OUT.PRINTLN ("Reading file" +z.getname ()); //Display file initial name
int x
while ( X=inout.read ())!=-1
System.out.write (x)
&N Bsp SYSTEM.OUT.PRINTLN ();
}
inout.close ();
}
}
Example 10-13 after running, create a ep10_13.zip compressed file in the program directory, and use the decompression software (such as WinRAR, etc.) to open it. At the command prompt, the results of the program running are as shown in Figure 10-12:
Figure 10-12 example 10_13 run results