chr*_*her 1 java resources properties
我最近发现自己面临着一个非常有趣的问题.properties我的应用程序中有一个文件,我试图从静态上下文中加载它.该properties文件是从一个类加载的Image,这是一个静态类.在Eclipse中它工作正常,但是当我尝试将其导出为JAR时,它显然不起作用.
prop.load(new FileInputStream(new File(Images.class.
getClassLoader().
getResource("config.properties").
toString())));
Run Code Online (Sandbox Code Playgroud)
这是我已尝试使用的行,但是当我尝试运行该程序时,它会抛出此错误:
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)
Run Code Online (Sandbox Code Playgroud)
我在这里有些不知所措,所以我的问题是:
如何从静态上下文加载资源,更重要的是,在执行此操作之前,是否需要将文件注册为资源?
编辑
经过一番搜索,我已经确定它getResource是返回的方法null.我想,现在我的大问题是为什么!?我的文件结构如下:
Project
src
controllers <-- This is where the Images class is.
models
views
img
doc
config.properties <-- This is the file I want.
Run Code Online (Sandbox Code Playgroud)
我不完全确定这会有什么帮助,但我仍然坚持寻找答案.
将属性文件放在与该类相同的目录中,然后使用该getResourceAsStream()方法.它将返回一个InputStream所以没有必要构建File.如果你把你的课程包装在一个罐子里,它也会继续工作......
Properties prop = new Properties();
prop.load(Images.class.getClassLoader().getResourceAsStream("config.properties"));
Run Code Online (Sandbox Code Playgroud)
或者从静态上下文:
prop.load(ClassLoader.class.getResourceAsStream("config.properties"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3671 次 |
| 最近记录: |