【问题标题】:How to read a property file of a project from another java project in eclipse如何在eclipse中从另一个java项目中读取项目的属性文件
【发布时间】:2015-11-19 07:57:07
【问题描述】:

我想从项目 Test1 (src/Test1.java) 中读取项目 Test 的 bean.properties 文件(在 src/conf/bean.properties 中)。我已经通过 java 构建路径引用了 Test1 中的 Test 并使用

Properties prop = new Properties();
prop.load(new FileInputStream("src/conf/bean.properties"));

我来了

java.io.FileNotFoundException: src\conf\bean.properties (The system cannot find the path specified)
    at java.io.FileInputStream.open0(Native Method)

【问题讨论】:

    标签: java eclipse properties-file


    【解决方案1】:

    考虑将您的属性文件放在类路径中。在 Eclipse 中它可能看起来像这样

    Project1
    +- src
       +- bean.properties
    
    Project2
    +- src
       +- ReadPropertiesTest.java
    

    然后转到 Project2 的属性,然后是“Java Build Path”,然后是“Projects”并将 Project1 添加到列表中。

    现在您可以像这样使用类加载器读取文件:

    InputStream stream = ReadPropertiesTest.class.getClassLoader()//
                                                 .getResourceAsStream("/bean.properties");
    Properties properties = new Properties();
    properties.load(stream);
    
    // ... closing code here
    

    注意属性文件名称前的斜线/

    【讨论】:

      【解决方案2】:

      这是读取属性文件的示例代码:-

      public class ReadPropertiesFile {
      public static void main(String[] args) {
          try {
              File file = new File("test.properties");
              FileInputStream fileInput = new FileInputStream(file);
              Properties properties = new Properties();
              properties.load(fileInput);
              fileInput.close();
      
              Enumeration enuKeys = properties.keys();
              while (enuKeys.hasMoreElements()) {
                  String key = (String) enuKeys.nextElement();
                  String value = properties.getProperty(key);
                  System.out.println(key + ": " + value);
              }
          } catch (FileNotFoundException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      }
      

      或者你可以使用:-

      Properties prop = new Properties();
      InputStream in = getClass().getResourceAsStream("foo.properties");
      prop.load(in);
      in.close();
      

      【讨论】:

        【解决方案3】:

        这样的事是不可能的!!!您必须指定绝对路径才能访问存在于类路径之外的文件。 每当您编写“src/conf/bean.properties”时,它都会指定该文件的相对路径。此类文件将仅在类路径中搜索。

        【讨论】:

          猜你喜欢
          • 2014-02-06
          • 2013-07-23
          • 1970-01-01
          • 1970-01-01
          • 2013-10-19
          • 2011-07-31
          • 2013-04-05
          • 2013-01-12
          • 1970-01-01
          相关资源
          最近更新 更多