【问题标题】:How to access property file in user.home directory?如何访问 user.home 目录中的属性文件?
【发布时间】:2012-04-03 23:06:26
【问题描述】:

如何访问user.home 中名为test.property 的属性文件?

这不起作用:

public class Properties {

    private static java.util.Properties p = new java.util.Properties();

    static {
        try {
            String home = System.getProperty("user.home");
            home += "\\test.properties";
            System.out.println("User home: " + home);
            InputStream is = Properties.class.getResourceAsStream(home);
            p.load(is);

        } catch (FileNotFoundException e) {
            System.out.println("property file could not be found!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

【问题讨论】:

  • 顺便说一句,最好根据主类的包名将应用属性放到user.home的子目录中。这有助于避免 your(名称不佳)test.properties 覆盖 my(名称不佳)test.properties(反之亦然)。
  • @dooonot 供将来参考,“不起作用”不是描述问题的适当方式。发布代码是第一步,接下来是发布实际发生的事情,即你得到了什么输出、异常等。不要只是假设人们不仅会编译和运行你的代码,而且会得到相同的结果你是。

标签: java properties environment-variables


【解决方案1】:
File propsFile = new File(home, "test.properties");
InputStream is = new FileInputStream(propsFile);

您可能会发现user.home 不在应用程序的运行时类路径中。在这种情况下,请改用File

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 2014-04-07
    • 1970-01-01
    • 2023-03-29
    • 2015-07-24
    • 2012-10-11
    相关资源
    最近更新 更多