Use java.util.zip to compress data

Source: Internet
Author: User
Java extends the java.util.zip package to be compatible with zip data compression. It provides a series of classes for reading, creating, and modifying ZIP files.

Main classes:

Zipentry stores zip objects

Zipinputstream is an input filter stream used to read files in ZIP files.

Zipoutputstream: An output filter stream used to write files to the ZIP file port.

 

The following program demonstrates how to use the java.util.zip package to compress data:

 

 

/**
* Author suqiang
* Create on 2008-7-26
*/
Import java. Io .*;
Import java.util.zip .*;
Public class zip {

Public static final int buffer = 1024;
Public static void main (string [] ARGs ){
Try {
Fileoutputstream DEST = new fileoutputstream ("C: // suqiang.zip ");
Zipoutputstream out = new zipoutputstream (New bufferedoutputstream (DEST ));

Puttozip (new file ("C: // suqiang"), Out ,"");

Out. Close ();
} Catch (filenotfoundexception E1 ){
E1.printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
/**
* Put file (include directory) to zip file
* @ Param file: the file to be zipped
* @ Param out: The zipped file
* @ Param dir
* @ Throws ioexception
*/
Private Static void puttozip (File file, zipoutputstream out, string DIR) throws ioexception {

If (file. isdirectory ()){
File [] files = file. listfiles ();
Dir = dir + (dir. Length () = 0? "": "/") + File. getname ();
For (INT I = 0; I <files. length; I ++)
Puttozip (files [I], out, DIR );
} Else {
Byte [] DATA = new byte [buffer];
Fileinputstream Fi = new fileinputstream (File );
Bufferedinputstream origin = new bufferedinputstream (FI, buffer );
Dir = dir. Length () = 0? "": Dir + "/" + file. getname ();
Zipentry entry = new zipentry (DIR );
Out. putnextentry (entry );
Int count;
While (COUNT = origin. Read (data, 0, buffer ))! =-1)
Out. Write (data, 0, count );

Origin. Close ();
Fi. Close ();
}
}
}


 

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.