2016-08-02 44 views
0

我設置了方法來嘗試/捕獲此錯誤。我的問題是,即使在同一個包中顯式創建Trivia.txt時,它也會捕獲Trivia.txt的fileNotFoundException。我無法弄清楚爲什麼沒有找到該文件。我做了一些四處尋找我的問題的答案,並沒有運氣。總之,這裏是我的代碼Java FileNotFoundException雖然文件存在

public static void readFile(){ 
    try{ 
     File file = new File("Trivia.txt"); 
     FileReader fr = new FileReader(file); 
     BufferedReader br = new BufferedReader(fr); 

     while((line = br.readLine()) != null){ 
      System.out.println(line); 

     } 

     br.close(); 

    } 
    catch(FileNotFoundException e){ 
     System.out.println("file not found"); 
     System.out.println(); 
    } 
    catch(IOException e){ 
     System.out.println("error reading file"); 
    } 


} 

這裏的代碼只是一個由WindowComp級(完全無關類)靜態調用的TextHandler類的方法。該包是mainPackage,其中包含主要()和WindowComp()和textHandler()與Triva.ondxt

+0

你是什麼意思,「在包裝中創建?」請顯示您的目錄結構。 – OldProgrammer

回答

2

嘗試加載文件作爲一種資源,像這樣

URL fileURL = this.getClass().getResource("Trivia.txt"); 
File file = new File(fileURL.getPath()); 

這將從同一個包誰加載資源類的加載文件。

如果發現從類的當前包的地方離該文件還可以爲您提供文件的絕對路徑,使用

URL fileURL = this.getClass().getResource("/my/package/to/Trivia.txt"); 
+0

非常感謝,效果很棒! –

4

你打開文件的方式,它應該可以在當前工作目錄中找到,而不是在子目錄中找到源被找到。

嘗試System.out.println(file.getCanonicalPath())爲了找出代碼期望文件的位置。

+0

我發現'getAbsolutePath()'通常也可以工作,並且拋出的異常更少。 –