我正在尝试从文件中读取输入,并将其放入 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/