简体   繁体   English

getClass()。getResource(“/”)在命令行中返回null

[英]getClass().getResource(“/”) returns null in command line

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. 当通过eclipse运行时,url对象获取正确的值。

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. 我使用文件浏览器打开了我的Jar文件并进行了检查。 It has the 'file.txt' in "/" location inside the Jar. 它在Jar内的“/”位置有'file.txt'。

Where am I going wrong ? 我哪里错了?

There are (often) no directories inside jar files. jar文件中通常没有目录。 Therefor it will return null . 因此它将返回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");

您应该将该文件移动到CLASSPATH中,并按以下方式获取:

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

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

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