读取Jar文件的内容可以通过JarInputStream来实现(继承于ZipInputStream)。
Java中通过ZipEntry来表示Jar中的一项。
JarInputStream提供getNextEntry()方法以遍历Jar文件中的每一项。
JarInputStream提供getManifest()方法以获取Manifest中定义的信息。
JarInputStream提供read()方法以读取每一项的内容。
具体实现如下:
private byte[] loadClassData(String name)
throws ClassNotFoundException {
JarInputStream jarInputStream = null;
try {
jarInputStream = new JarInputStream(new FileInputStream(jarFilename));
} catch (FileNotFoundException e) {
throw new ClassNotFoundException(jarFilename + " doesn't exist", e);
} catch (IOException e) {
throw new ClassNotFoundException("Reading " + jarFilename + " error", e);
}
byte[] classData = null;
String location = name.replace('.', '/') + ".class";
while(true) {
ZipEntry entry = null;
try {
entry = jarInputStream.getNextEntry();
if(entry == null) break;
String entryName = entry.getName();
if(entryName.toLowerCase().endsWith(".class") &&
entryName.equals(location)) {
classData = readClassData(jarInputStream);
}
} catch(IOException e) {
System.err.println(e.getMessage());
}
}
if(classData == null) {
throw new ClassNotFoundException(name + " cannot be found");
}
return classData;
}
private byte[] readClassData(JarInputStream jarInputStream)
throws IOException {
ByteArrayOutputStream classData = new ByteArrayOutputStream();
int readSize = 0;
while(jarInputStream.available() != 0) {
// 注:有些时候,即使jarInputStream有超过BUFFER_SIZE的数据
// 也有可能读到的数据少于BUFFER_SIZE
readSize = jarInputStream.read(buffer, 0, BUFFER_SIZE);
// jarInputStream.available()好像不起作用,因而需要加入一下代码
if(readSize < 0) break;
classData.write(buffer, 0, readSize);
}
return classData.toByteArray();
}
873

被折叠的 条评论
为什么被折叠?



