Java: 扫描器在读取文件时不接受 try-catch class 错误
Java: Scanner not accepting try-catch class error when reading from file
在 Java 8 文档中写道,接收文件源作为参数的 Scanner 的构造函数抛出 FileNotFoundException
。
但是看看下面的代码:
try{
sc = new Scanner("Rede.txt"); //This archive already exists
}
catch(FileNotFoundException f){
f.printStackTrace;
}
finally{
sc.close();
}
当我 运行 它时,我得到类似的东西:
error:exception FileNotFoundException is never thrown in body of corresponding try statement
catch(FileNotFoundException f){
IOException
也是如此。奇怪的是,如果我扔掉 try-catch 部分,代码会编译。
这里有什么问题?
Scanner也可以扫描String。要明白我的意思,试试:
System.out.println( new Scanner("Rede.txt").next() );
它将打印Rede.txt
。
其他一些 类(例如 FileInputStream)将采用字符串路径,但 Scanner 不会。如果你想使用一个文件,你需要实际传递一个文件:
sc = new Scanner(new File("Rede.txt"));
在 Java 8 文档中写道,接收文件源作为参数的 Scanner 的构造函数抛出 FileNotFoundException
。
但是看看下面的代码:
try{
sc = new Scanner("Rede.txt"); //This archive already exists
}
catch(FileNotFoundException f){
f.printStackTrace;
}
finally{
sc.close();
}
当我 运行 它时,我得到类似的东西:
error:exception FileNotFoundException is never thrown in body of corresponding try statement
catch(FileNotFoundException f){
IOException
也是如此。奇怪的是,如果我扔掉 try-catch 部分,代码会编译。
这里有什么问题?
Scanner也可以扫描String。要明白我的意思,试试:
System.out.println( new Scanner("Rede.txt").next() );
它将打印Rede.txt
。
其他一些 类(例如 FileInputStream)将采用字符串路径,但 Scanner 不会。如果你想使用一个文件,你需要实际传递一个文件:
sc = new Scanner(new File("Rede.txt"));