Java implementation file compression and decompression [ZIP format, gzip format]

Source: Internet
Author: User
Tags crc32 create zip



Java implementation Zip decompression and compression is basically using the Java peptide and recursive technology, can be a single file and any Cascade folder compression and decompression, for some beginners is a good example.



Zip plays archive and compresses two roles; gzip does not archive files, only compresses individual files, so on UNIX platforms, command tar is typically used to create an archive file and then command gzip to compress the archive file.



The Java I/O class Library also includes classes that read and write compressed format streams. To provide compression, just wrap them outside the existing I/O class. These classes are not reader and writer, but subclasses of InputStream and Outstreamput. This is because the compression algorithm is for byte rather than character.



Related classes and interfaces:



Checksum interface: Interfaces implemented by class Adler32 and CRC32



Adler32: Using the ALDER32 algorithm to calculate the number of checksum



CRC32: Using the CRC32 algorithm to calculate the number of checksum



Checkedinputstream:inputstream derived classes that provide checksum checksum of the input stream for verifying the integrity of the data



Checkedoutputstream:outputstream derived classes that obtain checksum checksum of the output stream for verifying the integrity of the data



Deflateroutputstream: The base class for the compression class.



A subclass of Zipoutputstream:deflateroutputstream that compresses the data into a ZIP file format.



A subclass of Gzipoutputstream:deflateroutputstream that compresses data into gzip file format



Inflaterinputstream: The base class for the decompression class



A subclass of Zipinputstream:inflaterinputstream that can decompress data in a ZIP format



A subclass of Gzipinputstream:inflaterinputstream that can decompress data in a ZIP format



ZipEntry class: Represents a ZIP file entry



ZipFile class: This class is used to read entries from a ZIP file


Compress and decompress multiple files using zip


Java support for the ZIP Format Class Library is more comprehensive, it can be used to compress multiple files into a compressed package. This class library uses the standard ZIP format, so it can be compatible with a number of compression tools.



The Zipoutputstream class has a compression method set and the compression level used in compression, and Zipoutputstream.setmethod (int method) sets the default compression method for entries. As long as no compression method is specified for a single ZIP file entry, the compression method set by Zipoutputstream is used to store the default value Zipoutputstream.deflated (for compressed storage), can also be set to stored (which means that only the archive storage is packaged). Zipoutputstream after setting the compression method to deflated, we can further use the setlevel (int level) method to set the compression level, with a value of 0-9 a total of 10 levels (the greater the value, the greater the compression), the default is Deflater.default_compression=-1. Of course we can also set the compression method for a single condition by using the Setmethod method of the entry zipentry.



Class ZipEntry describes the compressed files stored in a zip file. The class contains information that can be used to set and get a zip entry. The class ZipEntry is used by Zipfile[zipfile.getinputstream (ZipEntry entry)] and zipinputstream to read the zip file, zipoutputstream to write to the zip file. Here are some useful methods: GetName () returns the entry name, Isdirectory () if it is a directory entry, returns True (the directory entry is defined as an entry whose name ends with '/'), Setmethod (int method) Sets the entry's compression method, which can be assumed Zipoutputstream.stored or Zipoutputstream. Deflated.



The following example we used the Apache ZIP Toolkit (the package is Ant.jar), because the Java type comes with the Chinese path is not supported, but the use of the same way, but the Apache compression tool more than the interface to set the encoding, 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 extract, and not use Java.util.zip.ZipInputStream to extract read, of course, Apache does not provide Zipinputstream class.



File compression:


package gizAction;
import java.io.*;
import java.util.zip.*;
* *
* @author Dana·Li
* <p>
*The program implements zip compression
* <p>
*The basic functions include Java core technologies such as polymorphism and recursion, which can compress and decompress single files and any cascaded folders. You need to customize the source input path and the target output path in your code.
* <p>
*In this code, compression is implemented
* /
public class ZipCompressing {
Private int k = 1; / / define recursion 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 is closed
System. Out. Println ("compression complete");
}
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 ("the" + K + "recursion");
K++;
} else {
Out. Putnextentry (New zipentry (base)); / / create a 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 is closed
}
}
* *
* 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
* <p>
*The basic functions include Java core technologies such as polymorphism and recursion, which can compress and decompress single files and any cascaded folders. You need to customize the source input path and the target output path in your code.
* <p>
*In this code, the implementation is the decompression part;
* /
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"); / / enter the 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 &amp;&amp; !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 succeeded");
}
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");
}
}




Use gzip to compress individual files


The gzip interface is simple, so you can use it if you only need to compress a stream. Of course it can compress the character stream, and can compress the byte stream, the following is a GBK encoded format of the text file compression. The usage of the compression class is very simple, as long as the output stream is wrapped up with gzipoutputstream or Zipoutputstream, and then the input stream is wrapped with gzipinputstream or zipinputstream. All that is left is normal 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: the character file here is in GBK encoding mode
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(
"e:/tmp/source.txt"), "GBK"));
//Use gzipoutputstream to wrap the OutputStream and make it specific compression characteristics. Finally, 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 file...);
Int c;
while ((c = in.read()) != -1) {
/ *
*Note: in this case, a character file is compressed. The front part is read as a character stream and cannot be directly stored in C, because C is already Unicode
*Code, so the information will be lost (of course, the coding format itself is not right), so here we need to use GBK to solve and save it.
* /
out.write(String.valueOf((char) c).getBytes("GBK"));
}
In.close ();
Out.close ();
System. Out. Println ("start reading compressed file...);
//Use gzipinputstream to wrap InputStream with decompression feature
BufferedReader in2 = new BufferedReader(new InputStreamReader(
new GZIPInputStream(new FileInputStream("test.txt.gz")), "GBK"));
String s;
//Read the contents of the compressed file
while ((s = in2.readLine()) != null) {
System.out.println(s);
}
In2.close ();
}
} 
    • Related articles recommended:
    • The path of Java learning-spring Httpinvoker Learning
    • Java Learning Path-burlap Learning
    • Calling the Python method in Java
    • This article from: Hobby Linux Technology Network
    • This article link: http://www.ahlinux.com/java/9576.html


Java implementation file compression and decompression [ZIP format, gzip format]


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.