Java FileNotFoundException,尽管文件在那里 [英] Java FileNotFoundException although file is there

查看:126
本文介绍了Java FileNotFoundException,尽管文件在那里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了尝试/捕获此错误的方法.我的问题是,即使我在同一包中显式创建了Trivia.txt,它也会捕获Trivia.txt的fileNotFoundException.我不知道为什么找不到该文件.我四处寻找问题的答案,但没有运气.无论如何,这是我的代码

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


}

这里的代码只是TextHandler类的一种方法,该方法由WindowComp类(完全不相关的类)静态调用.该软件包是mainPackage,其中包含与Triva.Txt

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.

您还可以使用

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

这篇关于Java FileNotFoundException,尽管文件在那里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆