如何从提取的jar文件中读取类文件?

时间:2016-06-19 11:35:48

标签: java class file-io jar

我想阅读位于 .class 包内的 .jar 文件。如何从.class包中读取可读的.jar文件?

我的环境是:

  • 语言版本:Java
  • 平台版本:Java 1.8.0_73
  • 运行时:Java(TM) SE Runtime Environment (build 1.8.0_73-b02)
  • VM Server:Java HotSpot(TM) 64-Bit Server VM (build 25.73-b02, mixed mode)
  • 操作系统:Windows 10 Home (64-bit) [build 10586]

修改

我提取的.class文件包含二进制和&编译后的字节码:

The .class file contains binary & compiled bytecode

我想要的输出:

The .java file - readable code

2 个答案:

答案 0 :(得分:9)

使用decompiler。我更喜欢使用Fernflower,或者如果您使用IntelliJ IDEA,只需从那里打开.class文件,因为它预装了Fernflower。

或者,转到javadecompilers.com,上传.jar文件,使用CFR并下载反编译的.zip文件。

但是,在某些情况下,反编译代码非常违法,因此,更愿意学习而不是反编译。

答案 1 :(得分:2)

以编程方式提取.zip / .jar个文件的内容

假设.jar文件是要提取的.jar / .zip文件。 destDir是提取它的路径:

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();
    java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
    if (file.isDirectory()) { // if its a directory, create it
        f.mkdir();
        continue;
    }
    java.io.InputStream is = jar.getInputStream(file); // get the input stream
    java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
    while (is.available() > 0) {  // write contents of 'is' to 'fos'
        fos.write(is.read());
    }
    fos.close();
    is.close();
}