1

我想将 jar 文件的整个文件结构作为树。我找到了很多解决方案。我将其部署为 zip 文件。我按照链接如何在 jar 文件中获取类的名称?

代码如下所示:

    public void getClassFromJar(String path) throws IOException {

    //ArrayList<String> classNames=new ArrayList<String>();
    ZipInputStream zip=new ZipInputStream(new FileInputStream(path));
    IntoEntry(zip);

    //return classNames;
}

public void IntoEntry(ZipInputStream zip) throws IOException {

    for(ZipEntry entry=zip.getNextEntry();entry!=null;entry=zip.getNextEntry()) {
        System.out.println("entry: "+entry.getName());
        if (entry.getName().endsWith(".jar")) {
            // How to do

        }

        if(entry.getName().endsWith(".class") && !entry.isDirectory()) {
            // This ZipEntry represents a class. Now, what class does it represent?
            StringBuilder className=new StringBuilder();
            for(String part : entry.getName().split("/")) {
                if(className.length() != 0) {
                    className.append(".");
                }
                className.append(part);
                if(part.endsWith(".class")) {
                    className.setLength(className.length()-".class".length());
                }
            }
            classNames.add(className.toString());
        }
    }

}

System.out.println("entry: "+entry.getName());D:\work\workspace\myjar\org.objectweb.asm_2.2.2.jar(It is not in classpath.)打印的结果 :

entry: output/
entry: output/dist/
entry: output/dist/lib/
entry: output/dist/lib/asm-2.2.2.jar
entry: output/dist/lib/asm-analysis-2.2.2.jar
entry: output/dist/lib/asm-attrs-2.2.2.jar
entry: output/dist/lib/asm-commons-2.2.2.jar
entry: output/dist/lib/asm-tree-2.2.2.jar
entry: output/dist/lib/asm-util-2.2.2.jar
entry: plugin.xml

如何进入这个jar文件中的jar文件?

4

1 回答 1

0

你可以试试:

public static void printJarContent(File jarFile) {  
    java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
    java.util.Enumeration enum = jar.entries();
    while (enum.hasMoreElements()) {
        java.util.jar.JarEntry file = (java.util.jar.JarEntry) enum.nextElement();
        // temp directory where the jar will be extracted
        java.io.File f = new java.io.File(DEST_DIR + java.io.File.separator + file.getName());
        String ext = Files.probeContentType(f.toPath());
        if(ext.equalsIgnoreCase("jar")) {
            // extract current nested jar to a DEST_DIR and then
            printJarContent(f);    
        }
    java.io.InputStream is = jar.getInputStream(file); // get the input stream
    while (is.available() > 0) {  
        //print out the (is.read()) or do whatever you want with it
    }
    is.close();
}
于 2013-10-09T09:57:02.540 回答