[英]Maven project doesn't put files in src/main/resources on classpath
I have a java project in Eclipse. 我在Eclipse中有一个Java项目。 I want a read file that is in a certain folder.
我想要读取某个文件夹中的文件。 I use this code:
我使用以下代码:
File file = new File("directory/filename.txt");
If I have a simple java project, with this layout: 如果我有一个简单的Java项目,则使用以下布局:
Project
|
+- src
+- lib
+- directory
|
+ filename.text
The code works fine and I can read the file. 代码工作正常,我可以读取文件。 If I now convert this project to a maven project, Not much changes in Eclipse except a pom.xml file is made and a target folder is added (revaling the previously hidden "bin" output folder which is now a regular folder. The layout becomes:
如果我现在将此项目转换为maven项目,则除了pom.xml文件和目标文件夹外,在Eclipse中所做的更改不多(恢复了以前隐藏的“ bin”输出文件夹,现在它是常规文件夹。布局变为:
Project
|
+- src
+- lib
+- bin
+- target
+- directory
| |
| + filename.text
+- pom.xml
Because I want to use the maven project setup, I removed the src folder and added 4 new source folders to my project in Eclipse: 因为我想使用Maven项目设置,所以我删除了src文件夹,并在Eclipse中的项目中添加了4个新的源文件夹:
I copied the filename.text
to the resources folder, which should automaticcaly put its content on the classpath. 我将
filename.text
复制到资源文件夹,该文件夹应自动将其内容放在类路径中。 My project layout becomes: 我的项目布局变为:
Project
|
+- src/main/java
+- src/main/resources
| |
| + filename.text
+- src/test/java
+- src/test/resources
+- lib
+- bin
+- target
+- pom.xml
Now I noticed that this code doesn't work (NoSuchFileException) 现在我注意到该代码不起作用(NoSuchFileException)
File file = new File("filename.txt");
But this code does work: 但是这段代码确实有效:
File file = new File("src/main/resources/filename.txt");
Note: the way I run my code is by running it in eclipse as a java project. 注意:我运行代码的方式是将其作为Java项目在eclipse中运行。 The file read code is a single line in my main method in my main class.
在我的主类的main方法中,文件读取代码仅占一行。
I'm wondering what configuration I missed so that eclipse/maven regards the src/main/resources folder to be at the root of my classpath, rather than just a random folder that I have to explicitly name. 我想知道我错过了什么配置,因此eclipse / maven认为src / main / resources文件夹位于类路径的根目录下,而不只是我必须明确命名的随机文件夹。 It's especially weird, because another file in the resources folder, namely log4j.properties, is found and used by my log4j library without any problems.
这特别奇怪,因为我的log4j库找到并使用了资源文件夹中的另一个文件log4j.properties,没有任何问题。
Note: If I build my project and install it in my local repository, I can actually see both files (filename.txt and log4j.properties) being neatly under target/classes. 注意:如果构建项目并将其安装在本地存储库中,则实际上可以看到两个文件(filename.txt和log4j.properties)都整齐地位于目标/类下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.