[英]Java: Scanner not accepting try-catch class error when reading from file
在Java 8文檔中,據寫道,來自Scanner的構造函數接收到File Source作為參數,拋出了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部分,代碼就會編譯。
怎么了
掃描程序還可以掃描字符串。 要了解我的意思,請嘗試:
System.out.println( new Scanner("Rede.txt").next() );
它將打印Rede.txt
。
其他一些類(例如FileInputStream)將采用String路徑,但Scanner則不采用。 如果要使用文件,則需要實際將文件傳遞給它:
sc = new Scanner(new File("Rede.txt"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.