getClass()。getResource(" /")在命令行中返回null [英] getClass().getResource("/") returns null in command line

查看:154
本文介绍了getClass()。getResource(" /")在命令行中返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我正在使用

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

当通过eclipse运行时,url对象获取正确的值。

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

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

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

jar -cp myjar.jar SampleTest

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

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

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

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

我哪里出错?

推荐答案

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

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

如果你想获得您可以直接获得该资源的文件:

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

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

或者只是:

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

这篇关于getClass()。getResource(" /")在命令行中返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆