java getClass().getResource("/") 在命令行中返回 null

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

getClass().getResource("/") returns null in command line

javamavenjarclasspathclassloader

提问by user691197

I'm trying to read a file in my maven project at /src/main/resources/file.txt.

我正在尝试读取位于 /src/main/resources/file.txt 的 Maven 项目中的文件。

I'm using

我正在使用

URL url=this.getClass().getResource("/");
String filePath=url.getPath()+"file.txt";

url object gets the correct value when this is run thru eclipse.

url 对象在通过 Eclipse 运行时获得正确的值。

But, when I package the jar and run it in command line:

但是,当我打包 jar 并在命令行中运行它时:

jar -cp myjar.jar SampleTest

It returns null for 'url' object and throws a NullPointerException in the next line.

它为 'url' 对象返回 null,并在下一行抛出 NullPointerException。

I have openend my Jar file using file browser and checked. It has the 'file.txt' in "/" location inside the Jar.

我已经使用文件浏览器打开了我的 Jar 文件并进行了检查。它在 Jar 内的“/”位置有“file.txt”。

Where am I going wrong ?

我哪里错了?

回答by dacwe

There are (often) no directories inside jar files. Therefor it will return null.

jar 文件中(通常)没有目录。因此它将返回null



If you want to get the file you could get that resource directly:

如果要获取文件,可以直接获取该资源:

URL fileUrl = getClass().getResource("/file.txt");
...

Or simply:

或者干脆:

InputStream fileInputStream = getClass().getResourceAsStream("/file.txt");

回答by duffymo

You should move that file into your CLASSPATH and get it like this:

您应该将该文件移动到您的 CLASSPATH 并像这样获取它:

InputStream is = this.getClass().getResourceAsStream("file.txt");