gpt4 book ai didi

java - 导出到可运行的 JAR 后找不到资源文件

转载 作者:搜寻专家 更新时间:2023-11-01 01:10:31 25 4
gpt4 key购买 nike

我的项目结构如下所示:

Tester  
\-- src
|-- hello.java
\-- vocabulary.csv

我使用 getResource 加载 csv 文件:

url = this.getClass().getResource("vocabulary.csv");
System.out.println(url.getPath());
new FileReader(url.getPath());

在我将项目导出到可运行的 jar 文件之前,该程序完全可以正常工作。即使 URL 仍然有效(他打印路径而不是 null),控制台也会显示:

jar:file:/home/malte/Desktop/vocs.jar!/main/vocabulary.csv
Exception in thread "main" java.io.FileNotFoundException: file:/home/malte/Desktop/vocs.jar!/main/vocabulary.csv (No such file or directory)

您能解释一下为什么会发生这种情况以及我该如何解决这个问题吗?

附言我正在使用 Xtend 而不是纯 Java

最佳答案

你需要使用

InputStream = this.getClass().getResourceAsStream();

将源代码打包为 jar 后。您只有一个文件:您的 jar。您的 vocabulary.csv 不再是文件系统上的独立文件。

您可以阅读更多 here .

关于java - 导出到可运行的 JAR 后找不到资源文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18151072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com