2012-10-19 42 views
1

打開文件中的Java下面的代碼片段會導致這個錯誤:在OS/X

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type FileNotFoundException 
String path = "/Users/jfaig/Documents/workspace/my_array/"; 
BufferedReader in = new BufferedReader(new FileReader(path + "Matrix.txt")); 

的路徑是有效的,因爲我可以看到這個代碼列出的文件:

File dir = new File(path); 
String[] chld = dir.list(); 
if(chld == null){ 
    System.out.println("Specified directory does not exist or is not a directory."); 
    System.exit(0); 
} else { 
    for(int i = 0; i < chld.length; i++){ 
     String fileName = chld[i]; 
     System.out.println(fileName); 
    } 
} 

我回顧了許多關於Java中OS/X路徑的文章,但沒有解決我的問題。我將在Windows PC上嘗試它,看看問題是否特定於OS/X和/或我的Eclipse安裝。

回答

0

java.lang.Error: Unresolved compilation problem:意味着javac輸出在真正錯誤列出,但在這裏重複它。 Unhandled exception type FileNotFoundException - Java中的異常必須明確捕獲或重新拋出。

3

它不會抱怨你的文件,但要求你在沒有找到文件的情況下進行處理。如果你想處理異常

public static void main(String[] args) throws FileNotFoundExcetion { 

,或者:

如果你不想爲這種情況做任何處理,與throws FileNotFoundException如更新您的方法簽名爲main方法,可以參考以下寫包裝上面的代碼中,如下一個try{}catch(FileNotFoundException fnfe){}塊:

try{ 
    File dir = new File(path); 
    String[] chld = dir.list(); 
    if(chld == null){ 
    System.out.println("Specified directory does not exist or is not a directory."); 
    System.exit(0); 
    } else { 
    for(int i = 0; i < chld.length; i++){ 
     String fileName = chld[i]; 
     System.out.println(fileName); 
    } 
    }    
    }catch(FileNotFoundException fnfe){ 
    //log error 
    /System.out.println("File not found"); 
}   
0

讓Java的做文件分隔符的路徑和使用文件的構造函數有兩個參數。

File path = new File("/Users/jfaig/Documents/workspace/my_array"); 
File file = new File(path, "Matrix.txt"); 
System.out.println("file exists=" + file.exists()); // debug 
BufferedReader in = new BufferedReader(new FileReader(file)); 

正如前面提到的,你需要趕上或有方法拋出IOException。