src目录外的引用属性文件

时间:2013-03-08 15:51:18

标签: java properties

如果我有以下目录结构,

+ SRC
++ com.foo.util
+++ FooProperties.java
+ foo.properties

如何在foo.properties中引用FooProperties作为资源流?我已经尝试将它添加到类路径并引用它,

FooProperties.class.getResourceAsStream("/foo.properties")

但我得到NullPointerException。我做错了什么?

1 个答案:

答案 0 :(得分:3)

如果您想将properties文件保留在src之外(与src相同的水平),那么您可以通过这种方式获取properties文件: -

try {
    InputStream fileStream = new FileInputStream(new File(
            "test.properties"));
    Properties props = new Properties();
    props.load(fileStream);
    String myPropValue = (String) props.get("test.prop");
    System.out.println(myPropValue);
} catch (FileNotFoundException e) {
} catch (IOException e) {
}

希望它有所帮助。您甚至可以使用上述方法编辑属性文件(不需要绝对路径)。

相关问题