2017-04-11 78 views
0

我不明白爲什麼我不斷收到FileNotFoundException? 我通過Eclipse使用Java,並試圖讀取一個整數的file.txt,我想將它們加在一起來測試它們,但不斷得到異常。爲什麼我不斷收到FileNotFoundException?

我已經將文件導入到eclipse中。 這是我的代碼和我得到的異常消息。

public class FileRead { 
    //fields 
    private Scanner s; 
    private int[] arr; 
    /** 
    * @throws FileNotFoundException 
    * 
    */ 
    public FileRead() throws FileNotFoundException{ 
     s = new Scanner(new File("lab1_data.txt")); 
     arr = new int[10000000]; 
     for(int i = 0;i < arr.length;i++){ 
      arr[i] = s.nextInt(); 
     } 

    } 

    public int addArr(){ 
     int a = 0; 
     for(int x: arr){ 
      a = a + x; 
     } 
     return a; 
    } 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     FileRead r = null; 
     try { 
      r = new FileRead(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
     r.addArr(); 
    } 

} 

java.io.FileNotFoundException: lab1_data.txt (The system cannot find the 
file specified) 
at java.io.FileInputStream.open0(Native Method) 
at java.io.FileInputStream.open(Unknown Source) 
at java.io.FileInputStream.<init>(Unknown Source) 
at java.util.Scanner.<init>(Unknown Source) 
at FileRead.<init>(FileRead.java:22) 
at FileRead.main(FileRead.java:44) 
Exception in thread "main" java.lang.NullPointerException 
at FileRead.main(FileRead.java:48) 
+0

因爲文件沒有項目的目錄中存在的異常被拋出。 –

回答

0
(new File("lab1_data.txt")); 

傳遞精確的目錄路徑 /文件夾名稱/ lab1_data.txt

+0

我一直試圖做到這一點,我得到了像C:\ xxx \ Desktop \ CS \ Labs \ src \ lab1_data.txt這樣的東西,並且我會得到相同的異常。然後,我在eclipse中右鍵單擊文件,並看到斜線正好相反,例如/Lab/src/lab1_data.txt。我改變了斜槓並修復了一切。 –

0

lab1_data.txt應該在類路徑中找到。閱讀文件的更好的方法是getResourceAsStream。簡單的谷歌搜索應該有所幫助。

0

檢查文件存在的位置,並在new File("...")處添加文件的完整路徑。

請注意,當前項目路徑並不總是與.java文件相同的路徑。

0

此代碼的工作

 String path=""; 
     File f=new File("lab1_data.txt"); 
     path=f.getAbsolutePath(); 
相關問題