我有一个 jar 文件的 URL 列表,我也有整个路径类名com.mycompany.myproject.Test
,我如何在这些 jar 文件中搜索并获取其中的 .class 文件?我用它来反编译。
String classname = "com.mycompany.myproject.Test";
URI uri = Tool.searchClass(jarList, classname);
// decompile .class
...
有这样的示例代码吗?
补充:Shell脚本很好,但是java代码中有没有办法可以完成这项工作?
补充:我刚刚写了一个静态方法java.util.jar.JarFile
来处理这个,希望这对其他人有帮助
以下代码经过测试并且可以正常工作:
/**
* Search the class by classname specified in jarFile, if found and destFolder specified
* Copy the .class file into destFolder with whole path.
* @param classname
* @param jarFile
* @param destFolder
* @return
*/
public static File searchCompressedFile(String classname, File jarFile, String destFolder) {
try {
// change classname "." to "/"
if(classname.contains(".")){
classname = classname.replace(".", "/");
}
JarFile jarF = new JarFile(jarFile);
Enumeration<JarEntry> jarEntries = jarF.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
if (jarEntry.getName().indexOf(classname) >= 0) {
String filePath = jarFile.getAbsolutePath();
System.out.println(classname + " is in " + filePath + "--" + jarEntry.getName());
if (destFolder != null && !"".equals(destFolder)) {
// Make folder if dest folder not existed.
File destF = new File(destFolder);
if (!destF.exists()) {
destF.mkdirs();
}
File f = new File(destFolder + File.separator + jarEntry.getName());
if(!f.getParentFile().exists()){
f.getParentFile().mkdirs();
}
InputStream is = jarF.getInputStream(jarEntry);
FileOutputStream fos = new java.io.FileOutputStream(f);
while (is.available() > 0) {
fos.write(is.read());
}
fos.close();
is.close();
return f;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Class not found in jar");
return null;
}