2015-02-23 17 views
-1

今天解決坐下來與我的教授了堅實的30分鐘。有效。希望這可以幫助別人。的Java:之前,我們想出了「嘗試」行之前創建的「掃描儀的FileInput」掃描器無法讀取.txt文件

廣泛的研究之後,我一直無法找出原因掃描儀不PIC了「hurricane.txt」我把它保存爲項目爲.txt。我正在使用NetBeans。任何幫助表示讚賞!

// Openning hurricane data file 


try{ 
    System.out.println("Openning hurricane data file..."); 
    Scanner fileInput = new Scanner(new File("hurricane.txt")); 
    } 
    catch(FileNotFoundException e){ 


    System.err.println("FileNotFoundException: " + e.getMessage()); 
     return; 
    } 
    System.out.println("File opened successfully..."); 
    System.out.println("Reading file..."); 

這是輸出我得到:

run: 
Openning hurricane data file... 
FileNotFoundException: hurricane.txt (The system cannot find the file specified) 
BUILD SUCCESSFUL (total time: 1 second) 
+1

我想你沒有你的類路徑hurricane.txt。嘗試添加它'的System.out.println的類路徑 – dpassy 2015-02-23 21:51:52

+3

後的結果(新文件(「hurricane.txt」)getAbsolutePath());',看看你真的有文件在這個位置。 – Pshemo 2015-02-23 21:52:50

+0

對此的唯一可能的解釋是該名稱不相同或文件不在正確的目錄中。下面的答案可以幫助你。哦,不要忘了在完成之後關閉流。您可能只想使用Java提供的Try-With-Resource語句。 – Nikita 2015-02-23 22:20:04

回答

0

要麼指定完整路徑或放置文本文件中的應用程序的工作目錄中,您可以打印出如下:

final String workingDir = System.getProperty("user.dir"); 
System.out.println("Current working directory: " + workingDir); 

然後確保文本文件在特定目錄中,並且文件名和擴展名匹配。

0

昨天我有同樣的問題。我犯的錯誤是我創建/添加了一個文件,我把它稱爲junkfile.txt。但是,因爲我這樣做,它有名字junkfile.txt.txt因爲.txt擴展名被添加全自動,所以將其稱爲junkfile.txt顯然沒有工作,我得到了它,我花了一段時間才能找出一個filenotfound例外。

因此,也許,如果你使用hurricane.txt.txt它將工作。

編輯:如果您在NetBeans的工作目錄做了一個文本文件,並把它稱爲hurricane.txt它會出現在項目列表作爲hurricane.txt.txt。

+0

在我們試圖在「嘗試」行之前創建「掃描儀文件輸入」之前,今天坐下來和我的教授打了30分鐘。希望這可以幫助別人。 – buick 2015-02-24 23:46:31

0

嘗試

File f = new File(this.getClass().getResource("hurricane.txt").toExternalForm());