8

我有一个使用 Java 1.8.0 162 的应用程序,我正在将其升级到 Java 10。我遇到的问题之一是

appProperties.getClass().getResourceAsStream("/application.properties")

开始在 Java 10 中返回 null。任何想法为什么?appProperties定义如下:

appProperties = new Properties();

这发生在静态方法中,以防万一。

该文件存在于src/main/resources/application.properties. 无论我是从 IntelliJ 还是从 Maven 生成的 jar 运行,都会发生这种情况。

我尝试添加:

<resources>
    <resource>
       <directory>src/main/resources</directory>
    </resource>
</resources>

对我pom.xml来说,但这没有效果。

使用以下命令打印类路径:

System.getProperty("java.class.path")

产生,作为第一个条目:

C:\Users\pupeno\Documents\Dashman\code\dashman\target\classes

其中包含 application.properties。

4

3 回答 3

9

该变量的类是系统类,它由不同的类加载器加载。

您应该使用自己的类之一。

于 2018-04-07T00:09:56.757 回答
6

我找到了一个解决方案,虽然我不完全理解为什么这行得通而有问题的行没有,但这有效:

Application.class.getResourceAsStream("/application.properties")

whereApplication只是我的应用程序中的一个类。

也许这与ochi指向的答案有关,并且Application.class正在使用我的类加载器并且appProperties.getClass()正在使用系统类加载器。但是,为什么它在 Java 8 和 10 上的表现会有所不同,这一点并不明显。

于 2018-04-06T23:58:30.987 回答
0

我在使用 Intellij 时遇到了同样的错误,解决方法是我需要添加我打算获取的特定资源的文件格式。导航 CRTL+ALT+s 或设置->编译器->资源模式:在该字段中输入文件扩展名。点击申请,然后ok

于 2020-07-07T06:38:46.700 回答