首页 > 解决方案 > 将资源文件夹目录从目标类更改为 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"。

如何将文件读取目录从目标更改为源文件夹而不是目标。这里附上项目结构

标签: javafileproperties-file

解决方案


我建议您构建一个实用程序类,这样您就可以轻松加载所需的所有属性,例如:

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


推荐阅读