Java错误:默认构造函数无法处理异常类型FileNotFound Exception

duk*_*bur 2 java file-io constructor compiler-errors

我正在尝试从一个文件中读取输入到Java applet中以显示为Pac-man级别,但我需要使用类似于getLine()的东西...所以我搜索了类似的东西,这个是我找到的代码:

File inFile = new File("textfile.txt");
FileInputStream fstream = new FileInputStream(inFile);//ERROR
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Run Code Online (Sandbox Code Playgroud)

我标记为"ERROR"的行给出了一个错误,指出"默认构造函数无法处理由隐式超级构造函数抛出的异常类型FileNotFoundException.必须定义一个显式构造函数."

我搜索过这个错误信息,但我发现的一切似乎与我的情况无关.

Ant*_*oly 7

在子类中声明一个显式构造函数抛出FileNotFoundException:

public MySubClass() throws FileNotFoundException {
} 
Run Code Online (Sandbox Code Playgroud)

或者使用try-catch块包围基类中的代码而不是抛出FileNotFoundException异常:

public MyBaseClass()  {
    FileInputStream fstream = null;
    try {
        File inFile = new File("textfile.txt");
        fstream = new FileInputStream(inFile);
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        // Do something with the stream
    } catch (FileNotFoundException ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            // If you don't need the stream open after the constructor
            // else, remove that block but don't forget to close the 
            // stream after you are done with it
            fstream.close();
        } catch (IOException ex) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
        }
    }  
} 
Run Code Online (Sandbox Code Playgroud)

不相关,但由于您正在编写Java小程序,请记住您需要对其进行签名才能执行IO操作.