Java FileNotFoundException although file is there

不打扰是莪最后的温柔 提交于 2019-12-12 04:27:03

问题


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(){
    try{
        File file = new File("Trivia.txt");
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        while((line = br.readLine()) != null){
            System.out.println(line);

        }

        br.close();

    } 
    catch(FileNotFoundException e){
        System.out.println("file not found");
        System.out.println();
    }
    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


回答1:


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



回答2:


The way you open the file, it's supposed to be found in the current working directory, not in the subdirectory your source is found.

Try System.out.println(file.getCanonicalPath()) in order to find out where the code is expecting the file.




回答3:


If the file is found somewhere away from the current package of the class, you can also provide an absolute path directly to the constructor:

File file = new File("path/to/file/Trivia.txt");

You can also use a different constructor such as the one indicated in this answer:
Java - creating new file, how do I specify the directory with a method?

For further information, there's always the documentation: https://docs.oracle.com/javase/7/docs/api/java/io/File.html



来源:https://stackoverflow.com/questions/38731172/java-filenotfoundexception-although-file-is-there

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