所以我有以下文件夹结构:
- 项目
- 库 (从此文件夹运行 jar)
- 属性(要加载的属性文件位于此文件夹中)
我正在尝试通过 X.class.getClassLoader().getResource("properties/fileName") 加载属性文件。此方法在 eclipse 中有效,但是当我使用 maven 构建 jar 时,它无法找到该文件,给出文件未找到异常。
我怀疑该文件夹不在类路径中,因为如果我运行 getClassLoader().getResources("") 属性文件夹永远不会显示。我尝试了之前关于 stackoverflow 的问题中的所有建议,但到目前为止没有一个有效。
我也尝试运行 java -cp 和 -classpath 但仍然失败。
最佳答案
使用 Maven 时,默认情况下,*.properties
等文件和任何其他不可编译的文件必须位于 src/main/resources
文件夹中才可用。
此外,我建议您使用Thread.currentThread().getContextClassLoader()
来获取正确的类加载器,以便加载资源。
无论如何,如果您想在类路径中拥有自定义文件夹,我建议您在 pom.xml
中添加为资源,如下所示:
<project>
...
<build>
...
<resources>
<resource>
<!-- The folder you want to be a resource (from project root folder), like: project/properties -->
<directory>properties</directory>
<!-- Filtering if Maven should post-process text files to find and replace ${key} params: in most cases, leave it false -->
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
关于java - 如何将外部文件夹添加到类路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29394932/