【问题标题】:Reading from config.file throws FileNotFoundException (no such file or directory)从 config.file 读取会引发 FileNotFoundException(没有这样的文件或目录)
【发布时间】:2020-12-19 09:12:02
【问题描述】:

这是我的项目结构

- 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(没有这样的文件或目录)

  • 我该如何解决?

【问题讨论】:

  • 试着把它读成ConfigFileReader.class.getResourceAsStream("/config.properties")
  • 它返回 null
  • 不会工作...

标签: java intellij-idea ioexception config-files


【解决方案1】:

您需要将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.

【讨论】:

  • 资源包默认与java包并排
  • @user14021516 :从仅用于保留 java 类的包中读取属性文件不是一个很好的设计。在这种情况下,您需要提供config.properties 文件的绝对路径。不过它会起作用,让我更新我的答案。
  • 那行得通...我应该把我的 config.properties 文件而不是资源包(默认生成)放在哪里?
  • 如果还没有,在与“src”文件夹相同的级别创建一个文件夹作为“resources”。并将所有与配置相关的文件保存在其中。就是这样。
  • @user14021516 :很高兴知道这有效,如果这对您有用,您可以接受我的回答并投票。
【解决方案2】:

当您在开始时执行“/”时,它会尝试从您的根目录读取。删除 / 并且只要 src/main/resources 中存在 config.properties,FileInputStream 应该能够选择配置文件。

ConfigFileReader.class.getResourceAsStream("config.properties")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2021-09-02
    • 2014-08-24
    相关资源
    最近更新 更多