Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

java - FileNotFoundException in src/main/resources

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 BufferedReader(new FileReader(new File("./temp.txt")));

I get an error:

Exception in thread "main" java.io.FileNotFoundException: emp.txt

all files under src/main/resources are placed in the root folder of the classpath under maven. So why cant the program find the file here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...