Christopher Evans Christopher Evans - 7 months ago 50
Java Question

Java FileNotFoundException although file is there

I set up the method to try/catch this error. My issue is that it catches the fileNotFoundException for Trivia.txt even when I explicitly created Trivia.txt in the same package. I can't figure out why the file is not being found. I did some looking around for the answer to my problem, and had no luck. Anyway, here's my code

public static void readFile(){
File file = new File("Trivia.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);

while((line = br.readLine()) != null){



catch(FileNotFoundException e){
System.out.println("file not found");
catch(IOException e){
System.out.println("error reading file");


The code here is just a method of the TextHandler class that is called statically by WindowComp class (totally unrelated class). The package is mainPackage which holds the main() and WindowComp() and textHandler() alond with Triva.Txt


Try loading your file as a Resource, like this

URL fileURL = this.getClass().getResource("Trivia.txt");
File file = new File(fileURL.getPath());

This will load your file from the same package of the class who loads the resource.

You can also provide an absolute path for your file, using

URL fileURL = this.getClass().getResource("/my/package/to/Trivia.txt");