Java错误:默认构造函数无法处理异常类型FileNotFound异常 [英] Java error: Default constructor cannot handle exception type FileNotFound Exception
问题描述
我试图从一个文件中读取输入到一个Java小程序以显示为吃豆人的水平,但我需要使用类似于getLine()...所以我搜索类似的东西,这是我发现的代码:
I'm trying to read input from a file to be taken into a Java applet to be displayed as a Pac-man level, but I need to use something similar to getLine()... So I searched for something similar, and this is the code I found:
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));
我标记为ERROR的行给我一个错误,说默认构造函数无法处理异常类型FileNotFoundException
The line I marked "ERROR" gives me an error that says "Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor."
我搜索过这个错误信息,但我发现的一切似乎与我的情况无关。 / p>
I've searched for this error message, but everything I find seems to be unrelated to my situation.
推荐答案
在你的子类中声明一个显式构造函数,引发 FileNotFoundException
:
Either declare a explicit constructor at your subclass that throws FileNotFoundException
:
public MySubClass() throws FileNotFoundException {
}
或者使用 try-catch
代码块代替基础类中的代码,而不是抛出 FileNotFoundException
exception:
Or surround the code in your base class with a try-catch
block instead of throwing a FileNotFoundException
exception:
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小程序,请记住,您需要对其进行签名以便执行IO操作。
Unrelated, but since you are coding a Java applet, remember that you will need to sign it in order to perform IO operations.
这篇关于Java错误:默认构造函数无法处理异常类型FileNotFound异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!