2013-04-20 45 views
0

讀書時,我試圖從FileNotFoundException異常從文本文檔

public static void printLines(String doc){ 

    Scanner input = null; 
    input = new Scanner(doc + ".txt")); 

    while(input.hasNext()){ 

     String nextLine = input.nextLine(); 
     System.out.println(nextLine); 

    } 

    input.close; 

} 

上面的代碼是在字符串文檔作爲一個參數,並打印出每一行的方法讀取文件。在我的主要中,我使用try catch塊來捕獲FileNotFoundException。但是,當我嘗試運行該程序時,它始終遇到FileNotFoundException。

我使用的Eclipse和文本文件和Java文件都在同一個「Java項目」。有什麼理由爲什麼我的方法不能讀取文本文件?請幫忙!

回答

0

你得到FileNotFoundException的原因是你正在使用Scanner的錯誤構造函數。

變化input = new Scanner(doc + ".txt"));

input = new Scanner(new File(doc + ".txt")));應該滿足您的需求。

2

試着在裏面打印doc。它可能也包括文件的擴展名。

例如,如果文檔是/home/user/Desktop/mySample.txt,則掃描程序將嘗試查找/home/user/Desktop/mySample.txt.txt,該文檔不可用,因爲您將再次連接分機.txt

相關問題