I have a URL list of jar files, also I have whole path classname like com.mycompany.myproject.Test
, how can I search in these jar files and get the .class file in it? I use it for decompiling.
String classname = "com.mycompany.myproject.Test";
URI uri = Tool.searchClass(jarList, classname);
// decompile .class
...
Any sample codes like this?
Add: Shell script is good, but is there a way in java code can do this job?
Add: I just wrote a static method by using java.util.jar.JarFile
to handle this, hope this helps other people
The following code is tested and works properly:
/**
* 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;
}