Java错误:默认构造函数无法处理exception类型FileNotFound Exception
我正在尝试从一个文件中读取输入到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));
我标记为“ERROR”的行给出了一个错误,指出“默认构造函数无法处理由隐式超级构造函数抛出的exception类型FileNotFoundException。必须定义一个显式构造函数。”
我搜索过这个错误信息,但我发现的一切似乎与我的情况无关。
在您的子类中声明一个抛出FileNotFoundException
的显式构造函数:
public MySubClass() throws FileNotFoundException { }
或者使用try-catch
块包围基类中的代码,而不是抛出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操作。
您需要使用try和catch来包围代码,如下所示:
try { File inFile = new File("textfile.txt"); FileInputStream fstream = new FileInputStream(inFile);//ERROR } catch (FileNotFoundException fe){ fe.printStackTrace(); } // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in));
这是猜测,因为我们没有完整的代码。
来自Javadoc:
public FileInputStream(File file) throws FileNotFoundException
这意味着当你像你一样执行新的FileInputStream()
,它可以返回FileNotFoundException
。 这是一个经过检查的exception,您需要重新抛出(即在执行新操作的方法中添加’throws FileNotFoundException’)或catch(请参阅其他try / catch响应)。