【Java学习笔记】操作JAR文件
作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/
JAR文件是一种具有特定构造的zip文件
1.JAR文件的创建:
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 fis = new FileInputStream("manifest");
Manifest man = new Manifest(fis);//创建manifest文件
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 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.JAR文件的读取
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 jarfile = new JarFile(filename);
Enumeration entrylist = jarfile.entries();
while(entrylist.hasMoreElements()) {
JarEntry jarentry = (JarEntry)entrylist.nextElement();
System.out.println(jarentry.getName());
}
jarfile.close();
} catch(IOException e) {
System.out.println(e);
}
}
}
3.JAR文件的解压
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 jarfile = new JarFile(jarfilename);
Enumeration entrylist = jarfile.entries();
while(entrylist.hasMoreElements()) {
JarEntry 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);
}
}
}
作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/
以上是 【Java学习笔记】操作JAR文件 的全部内容, 来源链接: utcz.com/z/392741.html