首页 > 解决方案 > 从 config.file 读取会引发 FileNotFoundException(没有这样的文件或目录)

问题描述

这是我的项目结构

- src
-- java
--- utils
---- ConfigFileReader
--- resources
---- config.properties

这是ConfigFileReader类:

public class ConfigFileReader {

    public static String getProperty(String key) {
        Properties properties = new Properties();
        try {
            InputStream inputStream = new FileInputStream("/config.properties");
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties.getProperty(key);
    }
}

这是我的config.properties文件:

account_storage_technology=cognito

不幸的是,执行该方法会抛出

java.io.FileNotFoundException: /config.properties (没有这样的文件或目录)

标签: javaintellij-ideaioexceptionconfiguration-files

解决方案


您需要将resources文件夹与src. 像这样:

- src
 - java
  - utils
    - ConfigFileReader
- resources
  - config.properties

并修改路径如下:

InputStream inputStream = new FileInputStream("resources/config.properties");

更新:将属性文件保存在包中并从那里读取它是不可取的,也不是一个好主意。但是,您可以通过显示绝对完整路径让您的代码读取文件。

例子 :

InputStream inputStream = new FileInputStream("C:\\Project-Path\\Project-Name\\src\\java\\resources\\config.properties");

// Project-Path : This is the path where your Project Parent folder resides.
// Project-Name : This is the name of your project.

推荐阅读