java - 从 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 (没有这样的文件或目录)
- 我该如何解决?
解决方案
您需要将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.
推荐阅读
- regex - 匹配具有可变参数和可选后缀的字符串也与一个
- python - 如何从任何单词中删除“ing”
- c# - 如何在运行时从控件中克隆值更改事件
- ios - How to decrypt a very long string of AES 256 (CBC) encryption in Flutter?
- laravel - Generate Artisan command instead of "php artisan serve"
- postgresql - 为什么在我的情况下没有使用这个 GIN 索引(jsonb)
- python-3.x - “粘性”参数根本不会改变窗口
- php - 如何使用 gcloud 存储密钥文件从本地计算机进行身份验证
- c# - 如何确保在没有构造函数的情况下正确初始化对象?
- javascript - 对象数组中的舍入值