【问题标题】:Changing resource folder directory from Target classes to source in Java将资源文件夹目录从目标类更改为 Java 中的源
【发布时间】:2018-12-28 16:15:32
【问题描述】:

我正在尝试在我的 Java Web 应用程序中从 src/main/resources 读取属性文件。 问题是当我尝试使用以下代码加载文件时

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”。

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

【问题讨论】:

  • @Leviand 使用实用程序类帮助我读取属性,但我正在尝试读取 URL(例如:C:\Users\amit\Upload 文件夹位置),来自 prop.getProperty(property) 的属性值;没有\即(C:UsersamitUpload文件夹位置)URL。如何从属性文件中读取URL属性

标签: java file properties-file


【解决方案1】:

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

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

【讨论】:

  • 它帮助我读取了属性,但我正在尝试读取 URL(例如:C:\Users\amit\Upload 文件夹位置),proper.getProperty(property) 中的属性值;没有\即(C:UsersamitUpload文件夹位置)URL。如何从属性文件中读取URL属性
【解决方案2】:

也许你想要这个:

InputStream inputStream = getClass().getResourceAsStream("/config.properties");

ByteArrayOutputStream bOut = new ByteArrayOutputStream();
byte[] buffer = new byte[4 * 1024];
while (true) {
  int readCount = inputStream.read(buffer);
  if (readCount < 0) break;
  bOut.write(buffer, 0, readCount);
}

String configContent = bOut.toString("UTF-8");

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    相关资源
    最近更新 更多