FileNotFoundException in src/main/resources

﹥>﹥吖頭↗ 提交于 2019-12-03 22:43:30
Paul Samsotha

If you're going to package the file in the class path, then read it as such.. from the class path.

Maven Structure

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.


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.
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.

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. Hence you can load through the classloader:

InputStream in = getClass().getResourcesAsStream("temp.txt")

For more information see Class#getResoucesAsStream.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!