访问Maven项目中的属性文件

时间:2016-02-19 10:38:05

标签: java maven properties path filenotfoundexception

我在src / test / java / com / pp / utils中有一个java文件。我需要从这个Java文件中访问src / test / resources中的属性文件example.properties。

我尝试过:

Properties prop = new Properties();
InputStream input = null;

try {

    input = new FileInputStream("example.properties");

// load a properties file
    prop.load(input);

// get the property value and print it out
    System.out.println(prop.getProperty("key1"));

} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这会产生FileNotFound异常。路径应该是什么?或者我可以在哪里放置属性文件以便它被拾取?

2 个答案:

答案 0 :(得分:2)

InputStream inputStream = getClass().getResourceAsStream("/example.properties");

为清楚起见,假设您的属性文件位于/ src / test / resources中,这是类路径的根,因此是/example.properties。

答案 1 :(得分:0)

 InputStream  addrStream = <current-class>.class.getResourceAsStream("example.properties");

            prop .load(addrStream);

如果我的班级名称是PropertyUtil

InputStream  addrStream = PropertyUtil.class.getResourceAsStream("example.properties");

                prop .load(addrStream);

 InputStream  addrStream = getClass().getResourceAsStream("example.properties");

                    prop .load(addrStream);

如果您使用main method中的属性代码,请使用上面的第一个代码。