【问题标题】:How to read my property in war correctly?如何正确阅读我在战争中的财产?
【发布时间】:2021-10-05 21:58:28
【问题描述】:

我在阅读我的财产时遇到问题,我这样做:

    FileInputStream fis;
    Properties properties = new Properties(System.getProperties());
    fis = new FileInputStream(Objects.requireNonNull(this.getClass().getClassLoader()
            .getResource("config.properties")).getFile());
    properties.load(fis);

在本地机器上,这很好用,但是当我部署我的应用程序时出现问题:

Caused by: java.io.FileNotFoundException: /content/MyProject-1.0-SNAPSHOT.war/WEB-INF/classes/config.properties (No such file or directory)

当我尝试查看是否有我需要的文件时,我找到了,但 java 找不到。

这是我项目的大致结构:

src/main/java/entities/PropertyInit.java - 从这里我尝试读取属性

src/main/resources/config.properties - 这是我的财产的路径

【问题讨论】:

  • 尝试将文件作为 ResourceBundle 获取,而不是手动作为 ClassLoader 的资源。试试ResourceBundle bundle = ResourceBundle.getBundle("config");。在这种情况下,它可能会对您有所帮助,但问题可能出在您引发战争的方式上。这里有一些ResourceBundle Javadoc JDk 1.8。也许这不是问题所在,正如我所说,问题在于你如何构建你的项目。

标签: java jboss war java-ee-8


【解决方案1】:

Java EE 的属性有点复杂。 Java servlet 企业应用程序及其受人尊敬的 .WAR 以不同方式编译和构建(即 Java 类、JSP 和其他资源的分配)。

本文:Where to place and how to read configuration resource files in servlet based application?为您提供了一些不错的解决方案。

src/main/resources/config.properties.properties 的路径看起来是正确的,查看 Java EE 类路径示例,您的代码应该看起来更像这样:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("config.properties");
Properties properties = new Properties();
properties.load(input);

【讨论】:

    猜你喜欢
    • 2011-12-17
    • 1970-01-01
    • 2018-09-13
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多