FileNotFoundException in src/main/resources

后端 未结 4 654
梦如初夏
梦如初夏 2020-12-16 11:48

i placed a file in my maven project under src/main/resources the files name is simply temp.txt.

When i try to open the file:

BufferedReader br = new          


        
相关标签:
4条回答
  • 2020-12-16 12:22

    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);
            }
        }
    }
    

    enter image description here

    enter image description here

    0 讨论(0)
  • 2020-12-16 12:22

    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.

    0 讨论(0)
  • 2020-12-16 12:29

    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.

    0 讨论(0)
  • 2020-12-16 12:39

    just give this as your path:

    BufferedReader br = new BufferedReader(new FileReader(new 
    File("src/main/resources/temp.txt")));
    
    0 讨论(0)
提交回复
热议问题