Java类路径和配置文件

编程入门 行业动态 更新时间:2024-10-28 18:35:26
本文介绍了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类路径和配置文件

本文发布于:2023-10-07 10:55:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1469208.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:配置文件   路径   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!