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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18151072/
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-08-11 22:49:44  来源:igfitidea点击:

Can't find resource file after exporting to a runnable JAR

javaxtend

提问by schrobe

I have a project structure that looks like this:

我有一个看起来像这样的项目结构:

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

I load the csv file using getResource:

我使用 getResource 加载 csv 文件:

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

The program works completly fine until I export the project to a runnable jar file. Even though the URL is still valid (he prints the path instead of null) the console shows this:

该程序完全正常工作,直到我将项目导出到可运行的 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)

Can you explain me why this happens and how I can solv the issue?

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

P.S. I am using Xtend instead of pure Java

PS 我使用的是 Xtend 而不是纯 Java

采纳答案by rocketboy

You need to use

你需要使用

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

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

once you package your source as a jar. You have just one file : your jar. Your vocabulary.csvis no longer a standalone file on filesystem anymore.

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

You can read more here.

您可以在此处阅读更多内容。