简体   繁体   English

Java 编译成 jar 后出现错误 getResource()

[英]Java error getResource() after compilation into jar

Yesterday I finally finished my JavaFX application which perfectly ran in IDE, but when I tried to convert it to a .jar file and then run it... it didn't work.昨天我终于完成了我的 JavaFX 应用程序,它完美地在 IDE 中运行,但是当我尝试将其转换为.jar文件然后运行它时... I found that my class can not import any .fxml file using getClass().getResource() .我发现我的 class 无法使用getClass().getResource()导入任何.fxml文件。
So I created a sample code which is trying to read text file CheckFile.txt .所以我创建了一个示例代码,它试图读取文本文件CheckFile.txt


Class path tree: Class 路径树:

.
├── ClassFileTry.iml
├── out
│   ├── artifacts
│   │   └── ClassFileTry_jar
│   │       └── ClassFileTry.jar
│   └── production
│       └── ClassFileTry
│           ├── com
│           │   └── company
│           │       ├── CheckFile.txt
│           │       └── Main.class
│           └── META-INF
│               └── MANIFEST.MF
└── src
    ├── com
    │   └── company
    │       ├── CheckFile.txt
    │       └── Main.java
    └── META-INF
        └── MANIFEST.MF

Sample java code:样品 java 代码:

public static void GetResource() {
    String result = null;
    String url = (Main.class.getResource("CheckFile.txt")).getPath();
    System.out.println("URL = " + url);

    try {
        Scanner reader = new Scanner(new File(url));
        while (reader.hasNextLine()) {
            String data = reader.nextLine();
            result = data;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    System.out.println(result);
}

Output error: Output 错误:

$ java -jar ClassFileTry.jar
URL = file:/home/tucna/Desktop/ClassFileTry/out/artifacts/ClassFileTry_jar/ClassFileTry.jar!/com/company/CheckFile.txt
java.io.FileNotFoundException: file:/home/tucna/Desktop/ClassFileTry/out/artifacts/ClassFileTry_jar/ClassFileTry.jar!/com/company/CheckFile.txt (No such file or directory.)
    at java.base/java.io.FileInputStream.open0(Native Method)
    at java.base/java.io.FileInputStream.open(FileInputStream.java:211)
    at java.base/java.io.FileInputStream.<init>(FileInputStream.java:153)
    at java.base/java.util.Scanner.<init>(Scanner.java:639)
    at com.company.Main.GetResource(Main.java:49)
    at com.company.Main.main(Main.java:18)
null

I am using Linux and IntelliJ with java 15.0.2我正在使用 Linux 和 IntelliJ 与 java 15.0.2
So my questions are: What am I doing wrong and how to fix it?所以我的问题是:我做错了什么以及如何解决它? Why does getResourceAsStream() for reading files work and getResource() does not?为什么读取文件的 getResourceAsStream( getResourceAsStream()有效而getResource()无效?

I'll be very grateful for any help!我将非常感谢任何帮助! Thanks in advance!提前致谢!

java.io.File represents an actual file on disk. java.io.File代表磁盘上的实际文件。 Your resource is not that;你的资源不是这样的; it's an entry in a jar file.它是 jar 文件中的一个条目。 new File(someUrl) is a non-starter. new File(someUrl)是一个非首发。 The go-to alternative is to never use file for thus stuff, instead, check the API you're using, it tends to have an alternative form that takes a URL or InputStream .首选的替代方法是永远不要将文件用于此类内容,而是检查您正在使用的 API,它往往具有采用URLInputStream的替代形式。 So it is here, Scanner can also take an InputStream :所以在这里, Scanner 也可以采用 InputStream

try (InputStream in = Main.class.getResourceAsStream("/CheckFile.txt")) {
    Scanner s = new Scanner(in, StandardCharsets.UTF_8);
    // do you magic here.
} catch (IOException e) {
    throw new UncheckedIOException(e);
}

You could read your resource as stream.您可以将资源读取为 stream。 Try this:尝试这个:

    StringBuilder builder = new StringBuilder();

    try (InputStream is = Main.class.getResourceAsStream("/CheckFile.txt")) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while((line = reader.readLine()) != null) {
            if (builder.length() > 0) {
                builder.append("\n");
            }
            builder.append(line);
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "", ex);
        throw new UncheckedIOException(ex);
    }

    System.out.println(builder.toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM