java 如何使用绝对路径读取配置文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25724139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:32:55  来源:igfitidea点击:

How to read configuration file using absolute path?

javapluginseclipse-plugineclipse-rcp

提问by John Smith

I have a configuration file from which I have to read some properties. This configuration file exists in diferent locations but has the same name. I am able to read a configuration file, but only one from my project. I used the following code:

我有一个配置文件,我必须从中读取一些属性。此配置文件存在于不同的位置,但具有相同的名称。我能够读取一个配置文件,但只能从我的项目中读取一个。我使用了以下代码:

Properties prop = new Properties();
    String propFileName = "config.properties";


    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

    try {
        prop.load(inputStream);
    } catch (IOException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    if (inputStream == null) {
        try {
            throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

I have to open the config file using the full path so instead of propFileName="config.properties" to insert the absolute path to the config file. The config file can't be opened if I use the absolute path. How can this be done ?

我必须使用完整路径打开配置文件,而不是 propFileName="config.properties" 插入配置文件的绝对路径。如果我使用绝对路径,则无法打开配置文件。如何才能做到这一点 ?

回答by greg-449

InputStream inputStream = new FileInputStream("path");

will open a file with an absolute path.

将打开一个带有绝对路径的文件。

Note: This will only work for a file, it will not work for anything included in a plugin jar.

注意:这仅适用于文件,不适用于插件 jar 中包含的任何内容。

回答by Sridhar

You can use FileInputStream for locating config file outside of your project path.

您可以使用 FileInputStream 来定位项目路径之外的配置文件。

Properties prop = new Properties();
InputStream input = new FileInputStream("/home/ubuntu/Desktop/sample.properties");
prop.load(input);
System.out.println(prop.get("test"));

When specifying path we need give file name with extension.

指定路径时,我们需要提供带扩展名的文件名。