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 ();
}
}
}