从静态上下文加载属性文件

时间:2013-05-02 17:14:38

标签: java properties resources

我最近发现自己面临着一个非常有趣的问题。我的应用程序中有一个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.

我不完全确定这会有什么帮助,但我仍然难以找到答案。

1 个答案:

答案 0 :(得分:6)

将属性文件放在与该类相同的目录中,然后使用getResourceAsStream()方法。它将返回InputStream,因此无需构建File。如果你把你的课程打包在一个罐子里它也会继续工作......

Properties prop = new Properties();

prop.load(Images.class.getClassLoader().getResourceAsStream("config.properties"));

或者来自静态背景:

prop.load(ClassLoader.class.getResourceAsStream("config.properties"));