Java类路径和配置文件 [英] Java classpath and config file

查看:310
本文介绍了Java类路径和配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我使用:

  InputStream stream = myclass.class.getResourceAsStream(properties.file); 

properties.file位于配置目录下。



当使用eclipse运行程序时,它可以工作。
我刚刚在启动配置中的classpath中添加了config文件夹。



但是,如果我想运行这样的导出的jar:

  java -jar -cp C:\project\lib; C:\project\config myclass.jar 

我得到了非常棒的 java.lang.NullPointerException ,因为它不能找到该文件。



这听起来很经典而且愚蠢,但我找不到线索。
eclipse做什么我不做?



谢谢

解决方案

你不想把属性文件放在jar中相对于类)

  InputStream stream = myclass.class.getResourceAsStream( /properties.file); 

或简单地

 code> InputStream stream = myclass.class.getClassLoader()。getResourceAsStream(properties.file); 

然后确保包含此资源文件的目录的路径在运行时在类路径中指定该jar使得系统类加载器能够找到此资源。


I'm having some trouble finding a config file with classpath.

I use :

InputStream stream = myclass.class.getResourceAsStream("properties.file");

The properties.file is located under config directory.

When running the program with eclipse, it works. I just added config folder in the classpath in the launch configuration.

But If I want to run the exported jar like this :

java -jar -cp C:\project\lib;C:\project\config myclass.jar

I get the oh wonderful java.lang.NullPointerException because it can't find the file.

This sounds classic and stupid but I can't find a clue. What does eclipse do that I don't ?

Thanks

解决方案

You should use absolute path for class (If you don not want to put the properties file in your jar relative to the class)

InputStream stream = myclass.class.getResourceAsStream("/properties.file");

or simply

InputStream stream = myclass.class.getClassLoader().getResourceAsStream("properties.file");

And then ensure that the path to the dir containing this resource file is specified in the classpath when you run the jar so that the systemclassloader will be able to find this resource.

这篇关于Java类路径和配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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