Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/
1. Create a zip file
Import java.util.zip. zipentry;
Import java.util.zip. zipoutputstream;
Import java. Io. file;
Import java. Io. fileoutputstream;
Import java. Io. fileinputstream;
Import java. Io. ioexception;
Public class zipcreate {
Public static void main (string Arg []) {
Zipcreate ZC = new zipcreate ();
ZC. Create ("testfile.zip", ARG );
}
Public void create (string zipfilename, string filename []) {
Byte block [] = new byte [256];
Int length;
Try {
// Fileoutputstream-> zipoutputstream
Fileoutputstream Fos = new fileoutputstream (zipfilename );
Zipoutputstream out = new zipoutputstream (FOS );
For (INT I = 0; I <FILENAME. length; I ++ ){
// Fileinputstream-> zipentry
Fileinputstream in = new fileinputstream (filename [I]);
String name = filename [I]. Replace (file. separatorchar ,'/');
Zipentry = new zipentry (name );
Out. putnextentry (zipentry );
// In-> out
While (length = in. Read (Block)> 0)
Out. Write (Block, 0, length );
Out. closeentry ();
In. Close ();
}
Out. Close ();
} Catch (ioexception e ){
System. Out. println (E );
}
}
}
2. Read ZIP files
Iimport java.util.zip. zipfile;
Import java.util.zip. zipentry;
Import java. util. enumeration;
Import java. Io. ioexception;
Public class ziplist {
Public static void main (string Arg []) {
Ziplist ZL = new ziplist ();
ZL. List ("testfile.zip ");
}
Public void list (string filename ){
Try {
Zipfile = new zipfile (filename );
Enumeration entrylist = zipfile. Entries ();
While (entrylist. hasmoreelements ()){
Zipentry = (zipentry) entrylist. nextelement ();
System. Out. println (zipentry. getname ());
}
Zipfile. Close ();
} Catch (ioexception e ){
System. Out. println (E );
}
}
}
3. decompress the ZIP file
Import java.util.zip. zipfile;
Import java.util.zip. zipentry;
Import java. util. enumeration;
Import java. Io. inputstream;
Import java. Io. fileoutputstream;
Import java. Io. ioexception;
Public class zipextract {
Public static void main (string Arg []) {
Zipextract ze = new zipextract ();
Ze. Extract ("testfile.zip ");
}
Public void extract (string zipfilename ){
Byte block [] = new byte [256];
Int length;
Try {
Zipfile = new zipfile (zipfilename );
Enumeration entrylist = zipfile. Entries ();
While (entrylist. hasmoreelements ()){
Zipentry = (zipentry) entrylist. nextelement ();
Inputstream in = zipfile. getinputstream (zipentry );
String newfilename = zipentry. getname ();
Fileoutputstream out = new fileoutputstream (newfilename );
While (length = in. Read (Block)> 0)
Out. Write (Block, 0, length );
In. Close ();
Out. Close ();
}
} Catch (ioexception e ){
System. Out. println (E );
}
}
}
Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/