[英]FileNotFoundException in src/main/resources
i placed a file in my maven project under src/main/resources the files name is simply temp.txt. 我在src / main / resources下的maven项目中放置了一个文件,文件名只是temp.txt。
When i try to open the file: 当我尝试打开文件时:
BufferedReader br = new BufferedReader(new FileReader(new File("./temp.txt")));
I get an error: 我收到一个错误:
Exception in thread "main" java.io.FileNotFoundException: \temp.txt
all files under src/main/resources are placed in the root folder of the classpath under maven. src / main / resources下的所有文件都放在maven下的classpath的根文件夹中。 So why cant the program find the file here? 那么为什么程序无法在这里找到文件呢?
If you're going to package the file in the class path, then read it as such.. from the class path. 如果您要将文件打包在类路径中,那么请从类路径中读取它。
Maven Structure Maven结构
src
main
resources
file.txt
After it builds, the file gets placed in the root of the class path. 构建之后,文件将放置在类路径的根目录中。 So use 所以使用
InputStream is = getClass().getResourceAsStream("/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The /
in front of file.txt
will bring you to the root, from whatever package the class is in. file.txt
前面的/
将带你到这个类所在的任何包的根目录。
UPDATE UPDATE
Test example 测试示例
package com.underdogdevs.stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class TestResourceFile {
public static void main(String[] args) throws IOException {
InputStream is = TestResourceFile.class.getResourceAsStream("/test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
just give this as your path: 把它作为你的道路:
BufferedReader br = new BufferedReader(new FileReader(new
File("src/main/resources/temp.txt")));
Had this problem when setting up integration tests in Jenkins. 在Jenkins中设置集成测试时遇到此问题。
The issue was caused by having the job inside a folder with spaces in the name. 该问题是由名称中包含空格的文件夹中的作业引起的。 So instead of having a workspace folder named foo bar
, Jenkins created foo%20bar
and the tests all failed with FileNotFoundException
. 因此,Jenkins没有一个名为foo bar
的工作区文件夹,而是使用FileNotFoundException
创建了foo%20bar
并且所有测试都失败了。
The solution is just to rename your folder so it doesn't have any spaces. 解决方案只是重命名您的文件夹,因此它没有任何空格。
Maven puts the files under /src/main/resouces/
into the default package of your classpath. Maven将/src/main/resouces/
下的文件放入类路径的默认包中。 Hence you can load through the classloader: 因此,您可以通过类加载器加载:
InputStream in = getClass().getResourcesAsStream("temp.txt")
For more information see Class#getResoucesAsStream . 有关更多信息,请参阅Class#getResoucesAsStream 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.