2011-12-26 121 views
1

我正在運行以下代碼以嘗試從文本文件讀取數據。我對Java相當陌生,一直在嘗試爲自己創建項目來練習。下面的代碼稍微修改了我最初嘗試讀取文本文件的內容,但由於某種原因,它每次都會捕獲異常。它試圖從中讀取的文本文件只有「hello world」。我認爲它不能找到文本文件。我把它放在與源代碼相同的文件夾中,它出現在源碼包中(我使用netbeans btw)。它可能只是需要導入不同,但我無法找到任何進一步的信息。如果我的代碼在這裏是相關的,那麼它在下面。爲什麼我會捕捉異常

package stats.practice; 

import java.io.*; 
import java.util.Scanner; 

public final class TextCompare { 

    String NewString; 

    public static void main() { 
     try { 
      BufferedReader in = new BufferedReader(new FileReader("hello.txt")); 
      String str; 
      while ((str = in.readLine()) != null) { 
       System.out.println(str); 
      } 
      in.close(); 
     } catch (IOException e) { 
     } 
     System.out.println("Error"); 
    } 
} 

回答

2

第一步,替換下面的代碼

catch (IOException e){} 

catch (IOException e) { e.printStackTrace(); } 

並且還替換

main() 

main(String[] args) 

這會告訴你確切的原因。然後你必須解決實際的原因。

現在對於Netbeans,文件hello.txt必須在您的Netbeans項目中。像

<project_dir> 
    | 
    -->hello.txt 
    -->build 
    -->src 
+0

謝謝。替換文本文件的位置是它所需要的。 – Zombian 2011-12-26 23:57:25

3

它不一定每次都會捕捉異常。您的System.out.println("Error");聲明不在catch塊中。因此,每次程序執行時都會執行它。

爲了解決這個問題,在大括號(catch (IOException e) {System.out.println("Error");}

7

catch塊中的右括號是錯誤的內移動它。將其移動到System.out.println("Error");以下。

public static void main(String[] args) { 
    try { 
     BufferedReader in = new BufferedReader(new FileReader("hello.txt")); 
     String str; 
     while ((str = in.readLine()) != null) { 
      System.out.println(str); 
     } 
     in.close(); 
    } catch (IOException e) { // <-- from here 
     System.out.println("Error"); 
     // or even better 
     e.printStackTrace(); 
    } // <-- to here 
} 

作爲防禦性編程的問題(預Java 7中至少),你應該在finally塊始終貼近資源:

public static void main(String[] args) { 
    BufferedReader in = null; 
    try { 
     in = new BufferedReader(new FileReader("hello.txt")); 
     String str; 
     while ((str = in.readLine()) != null) { 
      System.out.println(str); 
     } 
     in.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (in != null) { 
      try { 
       in.close(); 
      } catch (Exception e) {} 
     } 

     // or if you're using Google Guava, it's much cleaner: 
     Closeables.closeQuietly(in); 
    } 
} 

如果您使用的是Java 7,你可以利用自動資源管理通過try-with-resources

public static void main(String[] args) { 
    try (BufferedReader in = new BufferedReader(new FileReader("hello.txt"))) { 
     String str; 
     while ((str = in.readLine()) != null) { 
      System.out.println(str); 
     } 
     in.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

是的,但它應該打印比錯誤更好的東西,所以你可以看到問題是什麼。 – 2011-12-26 23:35:59

+0

當然,編輯... – 2011-12-26 23:36:35

+0

+1,因爲你快! – 2011-12-26 23:37:17

1

你有一個空的catch塊,這幾乎總是一個壞主意。嘗試把這裏:

... catch (IOException ex) { 
    ex.printStackTrace(); 
} 

而你應該很快看到發生了什麼。