【问题标题】:How to read configuration file using absolute path?如何使用绝对路径读取配置文件?
【发布时间】:2014-09-08 12:20:48
【问题描述】:

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

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();
        }
    }

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

【问题讨论】:

  • 使用绝对路径访问文件通常不是一个好主意。
  • 是的,但就我而言,我必须这样做....这是强制性的
  • 使用url(包中的路径)
  • 包外路径...
  • 如何像InputStream in = new FileInputStream(configFile);那样使用FileInputStream ??

标签: java plugins eclipse-plugin eclipse-rcp


【解决方案1】:
InputStream inputStream = new FileInputStream("path");

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

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

【讨论】:

    【解决方案2】:

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

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

    在指定路径时,我们需要给出带有扩展名的文件名。

    【讨论】:

    • 您打开的文件是如何插入到代码中的Properties 对象中的?
    • @tddmonkey 抱歉,我错过了电话。现在,我已经添加了它。感谢您指出。 +1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多