2014-03-12 104 views
0

我使用eclipse,並在正確的目錄(src文件夾)中有我的文本文件。我只想讀取文件並計算其中的所有單詞。出於某種原因,我得到一個文件未找到異常被拋出。Eclipse未找到文件?

這是我的代碼。

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

public class Tester { 

public static int getSizeOfDictionary(File dictionary) 
     throws FileNotFoundException { 
    int count = 0; 

    Scanner reader = new Scanner(dictionary); 
    while (reader.hasNextLine()) { 
     reader.nextLine(); 
     count++; 
    } 
    reader.close(); 
    return count; 
} 

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

    File test = new File("words.txt"); 

    System.out.println(getSizeOfDictionary(test)); 

    } 

} 

回答

3

你可以使用this.getClass() .getResource(「words.txt」),它將在當前類路徑中找到該文件。

從您可以使用的主要方法:Tester.class.getResource(「words.txt」)

+0

當我嘗試時,我得到一個錯誤,說我的測試類沒有getResourceAsFile方法。 – LeatherFace

+0

對不起,拼寫它我們爲你。請現在嘗試。 – Thom

+0

注意:OP:你可以忽略'this'只是爲了getClass()。getResourceAsFile(...)'':)' – sircapsalot

3

當Eclipse啓動JVM它設置當前目錄爲一般工程的基目錄(除非你修改默認當前目錄)

${workspace_loc}/project_name 

所以你需要你的File初始化改變

File test = new File("src/words.txt"); 

注意:

如果導出它罐子就不再工作這將只限於該項目結構,我想你只需要它作爲工作的一部分

+0

非常感謝你。有趣的,因爲我不記得添加src /上次我使用eclipse。 – LeatherFace

+0

和如果你從eclipse外部運行你的代碼? –

+0

那麼你將不得不從正確的位置使用正確的類路徑來運行它,OP的東西與eclipse項目結構 –

0

你必須使用屬性類的類路徑和源文件夾中訪問您的文件

你可以嘗試這樣的:

this.getClass()getResourceAsFile( 「words.txt」)

+0

-1因爲您不**必須**使用反射或屬性類。您可以使用@JigarJoshi所做的相對路徑。這可能會引起誤解 – sircapsalot

+0

現在檢查@sircapsalot –

+0

,它基本上是獲取源的類路徑的反射過程。 當它給出異常時,您可以輕鬆檢出堆棧跟蹤。這是反射的概念.... –