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")));
Exception in thread "main" java.io.FileNotFoundException: \temp.txt
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 get placed in the root of the class path. So use
InputStream is = getClass().getResourceAtStream("/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
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);
}
}
}