Java implements ZIP decompression and compression functions basically use Java's polypeptides and recursion technology, which can compress and decompress individual files and any cascading folders, which is a very good example for some beginners.
zip plays two roles: archiving and compression; gzip does not archive files, but only compresses a single file. Therefore, on UNIX platforms, the command tar is usually used to create an archive file, and then command gzip to compress the archive file.
The Java I/O class library also includes some classes that can read and write compressed format streams. To provide compression functions, just wrap them outside of existing I/O classes. These classes are not Reader and Writer, but subclasses of InputStream and OutStreamput. This is because the compression algorithm is targeted at byte rather than characters.
Related classes and interfaces:
Checksum interface: an interface implemented by classes Adler32 and CRC32
Adler32: Use Alder32 algorithm to calculate the number of Checksums
CRC32: Use the CRC32 algorithm to calculate the number of Checksums
CheckedInputStream: InputStream derived class, you can obtain the checksum of the input stream, which is used to verify the integrity of the data.
CheckedOutputStream: OutputStream derived class, you can obtain the checksum of the output stream, used to verify the integrity of the data
DeflaterOutputStream: The base class of the compressed class.
ZipOutputStream: A subclass of DeflaterOutputStream that compresses data into Zip file format.
GZIPOutputStream: A subclass of DeflaterOutputStream that compresses data into GZip file format
InflaterInputStream: base class for decompression
ZipInputStream: A subclass of InflaterInputStream, which can decompress Zip format data
GZIPInputStream: A subclass of InflaterInputStream, which can decompress Zip format data
ZipEntry class: represents a ZIP file entry
ZipFile class: This class is used to read entries from ZIP files
Use ZIP to compress and decompress multiple files
Java supports Zip format library in a relatively comprehensive way, and it is necessary to use it to compress multiple files into a compressed package. This class library uses the standard Zip format, so it is compatible with many compression tools.
The ZipOutputStream class has the compression method set and the compression level used in the compression method. zipOutputStream.setMethod(int method) sets the default compression method used for entries. As long as the compression method is not specified for a single ZIP file entry, the compression method set by ZipOutputStream is stored. The default value is ZipOutputStream.DEFLATED (indicates compression storage) and can also be set to STORED (indicates only package archive storage). After ZipOutputStream has set the compression method to DEFLATED, we can further use the setLevel(int level) method to set the compression level. The compression level value is 0-9, with a total of 10 levels (the larger the value, the more likely it is to compress). The default is Deflater.DEFAULT_COMPRESSION=-1. Of course, we can also set the compression method for a single condition through the setMethod method of the entry ZipEntry.
The ZipEntry class describes a compressed file stored in a ZIP file. The class contains multiple methods to set up and obtain information about ZIP entries. The ZipEntry class is used by ZipFile[zipFile.getInputStream(ZipEntry entry)] and ZipInputStream to read the ZIP file, and ZipOutputStream to write to the ZIP file. There are some useful methods: getName() returns the entry name, isDirectory() returns true if it is a directory entry (the directory entry is defined as an entry whose name ends with '/'), setMethod(int method) Set the compression method for the entry, which can be ZipOutputStream.STORED or ZipOutputStream .DEFLATED.
In the following example, we used the apache zip toolkit (the package is ant.jar), because the java type comes with it does not support Chinese paths, but the two are used the same way, but the apache compression tool has more interfaces to set encoding methods, and the others are basically the same. In addition, if you use org.apache.tools.zip.ZipOutputStream to compress, we can only use org.apache.tools.zip.ZipEntry to decompress, and cannot use java.util.zip.ZipInputStream to decompress and read. Of course, apache does not provide the ZipInputStream class.
File compression:
package gizAction;import java.io.*;import java.util.zip.*;/** * @author Dana・Li * <p> * The program implements ZIP compression [compression] * <p> * The general functions include the use of polymorphism, recursion and other JAVA core technologies, which can compress and decompress a single file and any cascading folder. The source input path and target output path need to be customized in the code. * <p> * In this section of code, the compression part is implemented*/public class ZipCompressing { private int k = 1; // Define the recursive number variable private void zip(String zipFileName, File inputFile) throws Exception { System.out.println("Compressing..."); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); BufferedOutputStream bo = new BufferedOutputStream(out); zip(out, inputFile, inputFile.getName(), bo); bo.close(); out.close(); // Output stream close System.out.println("Compression completed"); } private void zip(ZipOutputStream out, File f, String base, BufferedOutputStream bo) throws Exception { // Method overload if (f.isDirectory()){ File[] fl = f.listFiles(); if (fl.length == 0){ out.putNextEntry(new ZipEntry(base + "/")); // Create zip compression entry point base System.out.println(base + "/"); } for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + "/" + fl[i].getName(), bo); // Recursively traverse subfolders} System.out.println("th" + k + "sub-recursive"); k++; } else { out.putNextEntry(new ZipEntry(base)); // Create zip compression entry point base System.out.println(base); FileInputStream in = new FileInputStream(f); BufferedInputStream bi = new BufferedInputStream(in); int b; while ((b = bi.read()) != -1) { bo.write(b); // Write the byte stream to the current zip directory} bi.close(); in.close(); // Input stream close} } /** * Test* @param args */ public static void main(String[] args) { ZipCompressing book = new ZipCompressing(); try { book.zip("F://ziptest.zip",new File("F://ziptest")); } catch (Exception e) { e.printStackTrace(); } }}File decompression:
package gizAction;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;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.ZipInputStream;/** * @author Dana・Li * <p> * The program implements ZIP decompression [decompression] * <p> * The general functions include the use of polymorphic and recursion-like JAVA core technologies, which can compress and decompress individual files and any cascading folders. The source input path and target output path need to be customized in the code. * <p> * In this code, the decompression part is implemented; */ public class zipDecompressing { public static void main(String[] args) { // TODO Auto-generated method stub long startTime=System.currentTimeMillis(); try { ZipInputStream Zin=new ZipInputStream(new FileInputStream("F://ziptest.zip"));//Input source zip path BufferedInputStream Bin=new BufferedInputStream(Zin); String Parent="F://ziptest//"; //Output path (folder directory) File Fout=null; ZipEntry entry; try { while((entry = Zin.getNextEntry())!=null && !entry.isDirectory()){ Fout=new File(Parent,entry.getName()); if(!Fout.exists()){ (new File(Fout.getParent())).mkdirs(); } FileOutputStream out=new FileOutputStream(Fout); BufferedOutputStream Bout=new BufferedOutputStream(out); int b; while((b=Bin.read())!=-1){ Bout.write(b); } Bout.close(); out.close(); System.out.println(Fout+"Decompression successfully"); } Bin.close(); Zin.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } long endTime=System.currentTimeMillis(); System.out.println("Time-consuming: "+(endTime-startTime)+" ms"); } }Compressing a single file with GZIP
GZIP's interface is relatively simple, so if you only need to compress a stream, you can use it. Of course it can compress character streams and compress byte streams. Below is a text file that compresses GBK encoding format.
The usage of compression classes is very simple; just use GZIPOutputStream or ZipOutputStream to wrap the output stream, and then use GZIPInputStream or ZipInputStream to wrap the input stream. The rest are some ordinary I/O operations.
import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.util.zip.GZIPInputStream;import java.util.zip.GZIPOutputStream;public class GZIPcompress { public static void main(String[] args) throws IOException { //Prepare to compress a character file. Note that the character file here is a GBK encoding BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream( "e:/tmp/source.txt"), "GBK")); //Use GZIPOutputStream to wrap the OutputStream stream to make its specific compression characteristics, and finally a test.txt.gz compression package will be generated // and there is a file named test.txt in it BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream( new FileOutputStream("test.txt.gz"))); System.out.println("Start writing compressed files..."); int c; while ((c = in.read()) != -1) { /* * Note, here is a character file that is read in character streams, and c cannot be directly stored, because c is already Unicode * code, which will lose information (of course, the encoding format itself is wrong), so it must be solved with GBK and then stored. */ out.write(String.valueOf((char) c).getBytes("GBK")); } in.close(); out.close(); System.out.println("Start reading compressed file..."); //Use GZIPInputStream to wrap the InputStream stream to make it decompressed BufferedReader in2 = new BufferedReader(new InputStreamReader( new GZIPInputStream(new FileInputStream("test.txt.gz")), "GBK")); String s; //Read the contents in the compressed file while ((s = in2.readLine()) != null) { System.out.println(s); } in2.close(); }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.