【问题标题】:Reading filepath from properties file从属性文件中读取文件路径
【发布时间】:2013-08-28 13:11:19
【问题描述】:

我正在尝试从从属性读取的文件路径中读取文件,但我不断收到 FileNotFoundException(文件存在)。

test.properties:

test.value = "src/main/resources/File.csv"

加载属性.java:

public class LoadProperties {

   public static void main(String[] args) throws FileNotFoundException, IOException {

      Properties aProp = new Properties();
      aProp.load(new FileInputStream("src/main/resources/test.properties")); // works

      String filepath = aProp.getProperty("test.value");
      System.out.println(filepath); // outputs: "src/main/resources/File.csv"

      FileReader aReader = new FileReader("src/main/resources/File.csv"); // works
      FileReader aReader2 = new FileReader(filepath); // java.io.FileNotFoundException
   }
}

为什么在它上面的行正常工作时抛出这个异常? 我应该如何从属性提供的路径中读取文件?

【问题讨论】:

    标签: java file-io properties


    【解决方案1】:

    您不应该将 " 放在属性文件中。Java 将其视为:

    String file = "\"src/main/resources/File.csv\"";
    

    【讨论】:

      【解决方案2】:
      test.value =src/main/resources/File.csv
      

      您不需要在属性文件中使用双引号来表示连续的字符串。

      【讨论】:

        【解决方案3】:

        你可以编写自己的逻辑来读取属性文件,无论文件路径中是否有单引号或双引号

        String propertyFileLocation = "C:\a\b\c\abc.properties";
        try
            {
                fileInputStream = new FileInputStream(propertyFileLocation);
                bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
                properties = new Properties();
                String currentLine = null;
                String[] keyValueArray = null;
                while ((currentLine = bufferedReader.readLine()) != null) {
                    if (!currentLine.trim().startsWith("#")) {
                        keyValueArray = currentLine.split("=");
                        if (keyValueArray.length > 1) {
                            properties.put(keyValueArray[0].trim(), keyValueArray[1].trim().replace("\\\\","\\"));
                        }
                    }
                }
            } 
            catch (Exception e)
            {
                return null;
            }
        

        【讨论】:

          猜你喜欢
          • 2021-01-05
          • 1970-01-01
          • 2015-05-07
          • 2018-10-12
          • 1970-01-01
          • 1970-01-01
          • 2012-03-11
          • 1970-01-01
          • 2021-06-25
          相关资源
          最近更新 更多