【问题标题】:Java - Loading External Properties File - FileNotFoundExceptionJava - 加载外部属性文件 - FileNotFoundException
【发布时间】:2014-10-06 22:24:31
【问题描述】:

我编写了一个加载外部属性以在我的程序中使用的类,它是根据以下链接建模的:Load Properties File in Singleton Class。我已在此处 (FileNotFoundException with properties file) 和此处 (Java Properties File not loading) 阅读了有关如何加载外部属性文件的信息,但是我继续收到 FileNotFoundException。我的属性文件是外部的,与我的可执行 jar 位于同一目录中。

公共类 ExternalProperties 扩展属性{

private static ExternalProperties instance = null;
private Properties properties;
private static String location;

protected ExternalProperties() throws IOException {
    properties = new Properties();
    properties.load(getClass().getResourceAsStream("test.properties"));
}

public static ExternalProperties getInstance(){
    if(instance == null){
        try{
            instance = new ExternalProperties();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return instance;
}

public static void setLocation(String path){
    location = path;
}

}

我通过命令行传递属性文件的位置如:

java -jar chef-deploy-tests-0.0.0009-SNAPSHOT-jar-with-dependencies.jar test.properties

关于我做错了什么有什么建议吗?

【问题讨论】:

    标签: java properties


    【解决方案1】:

    这取决于您的 test.properties 文件的位置。

     * <li> If the name begins with a {@code '/'}
     * then the absolute name of the resource is the
     * portion of the name following the {@code '/'}.
     *
     * <li> Otherwise, the absolute name is of the following form:
     *
     * <blockquote>
     *   {@code modified_package_name/name}
     * </blockquote>
     *
     * <p> Where the {@code modified_package_name} is the package name of this
     * object with {@code '/'} substituted for {@code '.'}.
    

    【讨论】:

      【解决方案2】:

      我认为您的问题是 test.properties 不在您的类路径中。您现在运行它的方式只是将文件作为参数传递给应用程序。我认为您的意思是将其添加到应用程序的类路径中:

      java -jar chef-deploy-tests-0.0.0009-SNAPSHOT-jar-with-dependencies.jar -classpath .

      这将包括 java 类路径中当前目录中的所有文件。另一种选择可能是将 test.properties 文件放入单独的目录并指定该目录而不是 '.'

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-30
        • 2016-04-15
        • 2011-08-27
        • 2013-01-28
        • 1970-01-01
        • 2016-06-18
        • 1970-01-01
        • 2021-10-12
        相关资源
        最近更新 更多