【问题标题】:Access Properties File in a Maven Project在 Maven 项目中访问属性文件
【发布时间】:2016-05-31 21:39:44
【问题描述】:

我在 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 异常。路径应该是什么?或者我可以在哪里放置属性文件以便获取它?

【问题讨论】:

  • 总是将资源作为流来访问您的属性文件

标签: java maven properties path filenotfoundexception


【解决方案1】:
 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 中使用属性代码,请使用上面的第一个代码。

【讨论】:

    【解决方案2】:

    试试

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

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

    【讨论】:

    • 我尝试了上述方法。调试时,inputStream 为空。
    • @Tunaki 问题已被问到 example.properties 位于 classpth 的根目录,即 /example.properties。
    猜你喜欢
    • 2017-11-18
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 2011-04-22
    相关资源
    最近更新 更多