Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/
A jar file is a zip file with a specific structure.
1. Create a jar file:
Import java. util. Jar. jarentry;
Import java. util. Jar. jaroutputstream;
Import java. util. Jar. manifest;
Import java. Io. file;
Import java. Io. fileoutputstream;
Import java. Io. fileinputstream;
Import java. Io. ioexception;
Public class jarcreate {
Public static void main (string Arg []) {
Jarcreate ZC = new jarcreate ();
ZC. Create ("testfile. Jar", ARG );
}
Public void create (string jarfilename, string filename []) {
Byte block [] = new byte [256];
Int length;
Try {
// Fileinputstream-> manifest-> jaroutputstream
// ^
// |
// Fileoutputstream
Fileinputstream FCM = new fileinputstream ("Manifest ");
Manifest man = new manifest (FCM); // create a manifest File
Fileoutputstream Fos = new fileoutputstream (jarfilename );
Jaroutputstream out = new jaroutputstream (FOS, man );
For (INT I = 0; I <FILENAME. length; I ++ ){
Fileinputstream in = new fileinputstream (filename [I]);
String name = filename [I]. Replace (file. separatorchar ,'/');
Jarentry = new jarentry (name );
Out. putnextentry (jarentry );
// Fileinputstream-> fileoutputstream
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 jar files
Import java. util. Jar. jarfile;
Import java. util. Jar. jarentry;
Import java. util. enumeration;
Import java. Io. ioexception;
Public class jarlist {
Public static void main (string Arg []) {
Jarlist ZL = new jarlist ();
ZL. List ("testfile. Jar ");
}
Public void list (string filename ){
Try {
Jarfile = new jarfile (filename );
Enumeration entrylist = jarfile. Entries ();
While (entrylist. hasmoreelements ()){
Jarentry = (jarentry) entrylist. nextelement ();
System. Out. println (jarentry. getname ());
}
Jarfile. Close ();
} Catch (ioexception e ){
System. Out. println (E );
}
}
}
3. decompress the JAR File
Import java. util. Jar. jarfile;
Import java. util. Jar. jarentry;
Import java. util. enumeration;
Import java. Io. inputstream;
Import java. Io. fileoutputstream;
Import java. Io. ioexception;
Public class jarextract {
Public static void main (string Arg []) {
Jarextract ze = new jarextract ();
Ze. Extract ("testfile. Jar ");
}
Public void extract (string jarfilename ){
Byte block [] = new byte [256];
Int length;
Try {
Jarfile = new jarfile (jarfilename );
Enumeration entrylist = jarfile. Entries ();
While (entrylist. hasmoreelements ()){
Jarentry = (jarentry) entrylist. nextelement ();
Inputstream in = jarfile. getinputstream (jarentry );
String newfilename = jarentry. 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/