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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37906786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:56:31  来源:igfitidea点击:

How to read a class file from an extracted jar file?

javaclassfile-iojar

提问by Suriyaa

I want to read a .classfile that is located inside of a .jarpackage. How can I read a readable .classfile from a .jarpackage?

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

My environment is:

我的环境是:

  • Language version: Java
  • Platform version: Java 1.8.0_73
  • Runtime: 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)
  • Operating system: Windows 10 Home (64-bit) [build 10586]
  • 语言版本: Java
  • 平台版本: Java 1.8.0_73
  • 运行: Java(TM) SE Runtime Environment (build 1.8.0_73-b02)
  • 虚拟机服务器: Java HotSpot(TM) 64-Bit Server VM (build 25.73-b02, mixed mode)
  • 操作系统: Windows 10 Home (64-bit) [build 10586]


EDIT:

编辑:

My extracted .classfile that contains binary & compiled bytecode:

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

The .class file contains binary & compiled bytecode

.class 文件包含二进制和编译的字节码

The output I want:

我想要的输出:

The .java file - readable code

.java 文件 - 可读代码

回答by RoccoDev

Use a decompiler. I prefer using Fernflower, or if you use IntelliJ IDEA, simply open .class files from there, because it has Fernflower pre-installed.

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

Or, go to javadecompilers.com, upload your .jar file, use CFR and download the decompiled .zip file.

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

However, in some cases, decompiling code is quite illegal, so, prefer to learn instead of decompiling.

但是,在某些情况下,反编译代码是非常非法的,因此,与其反编译,不如学习。

回答by Aahash de Ruffy

Extract the Contents of .zip/.jarfiles programmatically

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

Suppose .jarfile is the .jar/.zipfile to be extracted. destDiris the path where it will be extracted:

假设.jarfile 是要提取的.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();
}