Eclipse 在 src/main/resources 中添加了 ** 的排除模式:如何读取资源文件?

Luk*_*uke 2 java eclipse resources m2eclipse maven

我使用 Eclipse (Oxygen.2 Release (4.7.2)) 和标准的 src/main/resources 文件夹创建了一个简单的 Maven 项目,并将其添加到类路径中。问题是 Eclipse**向 src/main/resources 文件夹添加了一个排除模式。这里有一些图片可以更好地说明情况:

在此处输入图片说明 在此处输入图片说明

你可以自己复现这种情况,只记得运行Maven -> Update project...

根据这个答案,这不是错误,而是正确的行为。

所以问题是:如何从 src/main/resources 读取资源文件?

我不能使用显式路径 src/main/resources 因为在编译结果中不会有这样的路径,我不能使用 .getResource 或 .getResourceAsStream 因为 Eclipse**在那个路径上放置了一个排除模式

Luk*_*uke 5

我写这个答案以防其他人有同样的问题。

我发现 Eclipse 中 src/main/resource 文件夹上的排除模式是正常的(请参阅上面链接的答案)。排除意味着它不是 Eclipse 处理 src/main/resources 文件夹编译,而是 Maven(准确地说是 Eclipse 的 Maven 插件,M2Eclipse)。在类路径中找不到这些资源的事实是由于 pom.xml 中存在排除项:

<resource>
    <directory>src/main/resources</directory>
    <excludes>
        <!-- these resources will be excluded from the classpath; they will not go in to the target/classes folder and will not be packaged into the artifact -->
        <exclude>**/*</exclude>
    </excludes>
</resource>
Run Code Online (Sandbox Code Playgroud)