java - 将资源文件夹目录从目标类更改为 Java 中的源
问题描述
我正在尝试从src/main/resources
我的 Java Web 应用程序中读取属性文件。问题是当我尝试使用以下代码加载文件时
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
它试图从目标类中获取文件并获取异常
java.io.FileNotFoundException: C:\Users\PL90169\Java%20Projects\MKPFileUploadService\target\classes\config.properties"。
如何将文件读取目录从目标更改为源文件夹而不是目标。这里附上项目结构
解决方案
我建议您构建一个实用程序类,这样您就可以轻松加载所需的所有属性,例如:
public static String getPropertyValue(String property) throws IOException {
Properties prop = new Properties();
String propFileName = "config.properties";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
return prop.getProperty(property);
}
所以如果在你的config.properties
文件中你放了类似的东西
exampleValue=hello
当你打电话时,getPropertyValue("exampleValue")
你会得到hello
推荐阅读
- django - 如何为 django 项目设置 apache2.conf 文件?
- python - 使用 PIL 压缩 JPEG 图像
- angular - 角度路由器重定向到第一个选项
- three.js - 当显式调用 AFrame 组件的 remove() 时,无法读取未定义错误的属性“object3D”
- redis - xargs:不匹配的单引号;默认情况下,引号对 xargs 是特殊的,除非您使用 -0 选项
- c++ - 只是停留在这段代码中,我必须创建一个数学表
- java - JPA OneToMany,如何在控制台或 webapp 中打印时忽略字段 ManyToOne
- r - gsub 的正则表达式匹配行直到和通过换行符 \n 字符
- java - 使用 volley 库在 Android 中进行 WP Rest API OAuth1 身份验证
- mongodb - 如何使用 mongodb 连接器在 talend 中获取 sysdate