使用 FileReader 会导致编译器错误“未处理的异常类型 FileNotFoundException"; [英] Using FileReader causes a compiler error "unhandled exception type FileNotFoundException"

查看:44
本文介绍了使用 FileReader 会导致编译器错误“未处理的异常类型 FileNotFoundException";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里阅读了一些与相同问题相关的主题,但解决方案不起作用.:/

Ive read a few threads here that relate the same problem, but the solutions arent working. :/

我使用 Eclipse,这是我的程序.

I use Eclipse, here is my program.

package mypackage;
import java.io.*;


public class myclass {


public static void main(String[] args) {
    //String myfile = "/home/jason/workspace/myproject/src/mypackage/myscript.abc";
    String myfile = "src/mypackage/myscript.abc";
    File file1 = new File(myfile);
    if(file1.exists()) {
        log(myfile + " exists. length : " + myfile.length());
    }
    else{
        log(myfile + " does not exist");
        //System.exit(1);
    }

    //FileReader fr = new FileReader("myscript.abc");//I uncomment this and die inside


    System.out.println("
AbsPath : " + new File(".").getAbsolutePath());
    System.out.println("
user.dir : " + System.getProperty("user.dir"));


}

public static void log(String s){
    System.out.println(s);
}

}

无论我尝试什么,或者我把 myscript.abc 放在哪里(现在它遍布整个项目目录),我得到的错误是这样的:

The error I get, no matter what I try, or where I put myscript.abc (its peppered throughout the projects directory now) is this :

未处理的异常类型FileNotFoundException myclass.java/myproject/src/mypackage

Unhandled exception type FileNotFoundException myclass.java /myproject/src/mypackage

脑残,扯毛.

推荐答案

未处理的异常类型 FileNotFoundException myclass.java/myproject/src/mypackage

Unhandled exception type FileNotFoundException myclass.java /myproject/src/mypackage

这是一个编译器错误.Eclipse 告诉你你的程序没有编译成 java 字节码(所以你当然不能运行它).现在,您可以通过简单地声明您的程序可能抛出此异常来修复它.像这样:

This is a compiler error. Eclipse is telling you that your program does not compile to java byte code (so of course you can't run it). For now, you can fix it by simply declaring that your program may throw this exception. Like so:

public static void main(String[] args) throws FileNotFoundException {

FileNotFoundException 是一个检查异常"(谷歌这个),这意味着代码必须说明 JVM 如果遇到它应该做什么.在代码中,try-catch 块或 throws 声明向 JVM 指示如何处理异常.

FileNotFoundException is a "checked exception" (google this) which means that the code has to state what the JVM should do if it is encountered. In code, a try-catch block or a throws declaration indicate to the JVM how to handle the exception.

为了将来参考,请注意 Eclipse 中的红色波浪下划线表示存在编译器错误.如果您将鼠标悬停在问题上,Eclipse 通常会建议一些非常好的解决方案.在这种情况下,一个建议是向 main 添加一个 throws 子句".

For future reference, please note that the red squiggly underline in Eclipse means there is a compiler error. If you hover the mouse over the problem, Eclipse will usually suggest some very good solutions. In this case, one suggestion would be to "add a throws clause to main".

这篇关于使用 FileReader 会导致编译器错误“未处理的异常类型 FileNotFoundException";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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