繁体   English   中英

访问Maven项目中的属性文件

[英]Access Properties File in a Maven Project

我在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异常。 应该走什么路? 还是可以在其他地方放置属性文件以使它被拾取?

尝试

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

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

 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中使用属性代码,请使用上面的第一个代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM