2015-01-09 38 views
2

在嘗試讀取文件時,我一直收到相同的錯誤。該文件存在於該目錄中,我做錯了什麼?java.io.FileNotFoundException - 目錄中存在文件

package test; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class MenuSample{ 

    public static void main(String[] args) { 

     File f = new File("C:/Users/Joe/Documents/workspace/ArtificialLifeFX/res/latest.txt"); 

     Scanner scanner = null; 
     try { 
      scanner = new Scanner(f); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     scanner.useDelimiter("\r\n"); 
    } 
} 

我得到以下錯誤:

java.io.FileNotFoundException: C:\Users\Joe\Documents\workspace\ArtificialLifeFX\res\latest.txt (The system cannot find the file specified) 
    at java.io.FileInputStream.open(Native Method) 
    at java.io.FileInputStream.<init>(Unknown Source) 
    at java.util.Scanner.<init>(Unknown Source) 
    at test.MenuSample.main(MenuSample.java:16) 
Exception in thread "main" java.lang.NullPointerException 
    at test.MenuSample.main(MenuSample.java:21) 

原諒我,如果我太天真,我是新來的Java。我在Windows 7上運行Eclipse Luna。

+1

幾個想法... Java是文件名區分大小寫,而Windows不是,所以確保大小寫匹配。 – Jeremy 2015-01-09 19:46:57

+0

另外,字符串中的分隔符是正斜槓,而窗口是反斜槓。我不確定Java是否足夠聰明來解決這個問題。 – Jeremy 2015-01-09 19:47:27

+0

爲了測試路徑是否真的存在,你可以嘗試打開一個shell並輸入'cd C:\ Users \ Joe \ Documents \ workspace \ ArtificialLifeFX \ res \' – wassgren 2015-01-09 19:52:46

回答

1

當它告訴你這些事情時,請相信JVM。沒有任何理由堅持你是正確的;你無法贏得這個論點。你需要弄清楚你做錯了什麼。

我的建議?試試這個:

File f = new File("C:\\Users\\Joe\\Documents\\workspace\\ArtificialLifeFX\\res\\latest.txt"); 

在我的Windows 7計算機將是:

File f = new File("C:\\Users\\Joe\\My Documents\\workspace\\ArtificialLifeFX\\res\\latest.txt"); 

檢查路徑,以確保它是絕對現貨上。

+0

仍然沒有運氣使用這些路徑。在調試代碼並打開存儲在Windows資源管理器中的變量'f'中的路徑時,正確加載.txt文件,所以我不確定Eclipse爲什麼沒有找到它...... – 2015-01-09 19:56:11

+1

使用'/'而不是' \\'沒有問題。 – Tom 2015-01-09 19:58:39

+0

你有沒有嘗試duffymo的最後/之間的水庫和最新取代\\路徑? – Duston 2015-01-09 20:03:44

0

文件可能存在,但eclipse沒有看到它。嘗試刷新項目瀏覽器中的項目,並確保該文件出現在項目瀏覽器下。由於您引用的文件位於工作空間文件夾下,因此它應該出現在項目瀏覽器中。

相關問題