我正在使用 Eclipse,并且我的文本文件位于正确的目录(src 文件夹)中。我只想读取文件并计算其中的所有单词。由于某种原因,我收到抛出文件未找到异常的消息。
这是我的代码。
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")
关于java - Eclipse 找不到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22360408/