Eclipse未找到文件?

问题描述:

我使用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)); 

    } 

} 

你可以使用this.getClass() .getResource(“words.txt”),它将在当前类路径中找到该文件。

从您可以使用的主要方法:Tester.class.getResource(“words.txt”)

+0

当我尝试时,我得到一个错误,说我的测试类没有getResourceAsFile方法。 – LeatherFace

+0

对不起,拼写它我们为你。请现在尝试。 – Thom

+0

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

当Eclipse启动JVM它设置当前目录为一般工程的基目录(除非你修改默认当前目录)

${workspace_loc}/project_name 

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

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

注意:

如果导出它罐子就不再工作这将只限于该项目结构,我想你只需要它作为工作的一部分

+0

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

+0

和如果你从eclipse外部运行你的代码? –

+0

那么你将不得不从正确的位置使用正确的类路径来运行它,OP的东西与eclipse项目结构 –

你必须使用属性类的类路径和源文件夹中访问您的文件

你可以尝试这样的:

this.getClass()getResourceAsFile( “words.txt”)

+0

-1因为您不**必须**使用反射或属性类。您可以使用@JigarJoshi所做的相对路径。这可能会引起误解 – sircapsalot

+0

现在检查@sircapsalot –

+0

,它基本上是获取源的类路径的反射过程。 当它给出异常时,您可以轻松检出堆栈跟踪。这是反射的概念.... –