我最近发现自己面临一个非常有趣的问题。我的应用程序中有一个 properties
文件,我试图从静态上下文加载它。 properties
文件是从 Image
类加载的,它是一个静态类。在 Eclipse 中它工作正常,但是当我试图将它导出为 JAR 时,它显然不起作用。
prop.load(new FileInputStream(new File(Images.class.
getClassLoader().
getResource("config.properties").
toString())));
这是我已经尝试使用的行,但是当我尝试运行该程序时,它会抛出此错误:
Exception in thread "main" java.lang.NullPointerException
at controllers.Images.loadImageFiles(Images.java:47)
at views.World.<init>(World.java:55)
at views.World.main(World.java:40)
我在这里有些不知所措,所以我的问题是:
如何从静态上下文加载资源,更重要的是,我是否需要在执行此操作之前将文件注册为资源?
编辑
经过一些搜索,我确定是 getResource
方法返回了 null
。我想,我现在最大的问题是为什么!?我的文件结构如下:
Project
src
controllers <-- This is where the Images class is.
models
views
img
doc
config.properties <-- This is the file I want.
我不完全确定这会有什么帮助,但我一直在寻找答案。
最佳答案
将属性文件放在与类相同的目录中并使用getResourceAsStream()
方法代替。它将返回 InputStream
所以不需要构造 File
.如果您将类打包在一个 jar 中,它也将继续工作...
Properties prop = new Properties();
prop.load(Images.class.getClassLoader().getResourceAsStream("config.properties"));
或者来自静态上下文:
prop.load(ClassLoader.class.getResourceAsStream("config.properties"));
关于java - 从静态上下文加载属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16343939/