Java错误: Default constructor cannot handle exception type FileNotFound Exception

标签 java file-io constructor compiler-errors

我正在尝试从文件中读取输入,并将其放入 Java 小程序中,以显示为吃 bean 人关卡,但我需要使用类似于 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));

我标记为“错误”的行给出了一个错误,指出“默认构造函数无法处理隐式 super 构造函数抛出的异常类型 FileNotFoundException。必须定义显式构造函数。”

我已经搜索过此错误消息,但我找到的所有内容似乎与我的情况无关。

最佳答案

要么在子类中声明一个显式构造函数,该构造函数会抛出 FileNotFoundException:

public MySubClass() throws FileNotFoundException {
} 

或者用 try-catch block 包围基类中的代码,而不是抛出 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);
        }
    }  
} 

不相关,但由于您正在编写 Java 小程序,请记住您将需要 sign it以便执行IO操作。

关于Java错误: Default constructor cannot handle exception type FileNotFound Exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9354791/

相关文章:

java - 通过maven将.jar文件添加到类路径

分割文件的c代码

c++ - 文件开头的垃圾字符

java - StringTokenizer 的问题

c# - 如何使泛型类成为另一个实例类中的属性?

java - JVM 安全点暂停,但仅当代码在方法中时才会暂停,并且不是 GC 参与

java - IE10向Spring Controller 发送双重post请求

Java序列化未实现 `Serializable`的字段

c - 在C中将数组存储在另一个数组(3D数组)中

javascript - 如何从构造函数返回数组并在 Javascript 中成功链接对象