无法在 Eclipse 中使用 Scanner 读取 txt 文件 (Java)



我在Eclipse(jre1.8.0_181(中为一个项目读取.txt文件(words.txt(时遇到困难。我在中有一份words.txt的副本

String wordsPath = "C:\Users\Administrator\Documents\words.txt";

以及项目目录本身(我试图用多种方式定义它(:

String workingDir = System.getProperty("user.dir");
String wordsPath2 = workingDir.concat("\words.txt");
String wordsPath3 = new File("").getAbsolutePath().concat("\words.txt");

但是,当我尝试建立filein:时

Scanner filein = new Scanner(new File(wordsPath));
filein = new Scanner(new File(wordsPath2));
filein = new Scanner(new File(wordsPath3));

我所有的尝试都得到了FileNotFoundException。有人对此有什么见解吗?我知道文件在那里;我还缺少什么?我相信我也有合适的进口产品(import java.io.File;import java.util.Scanner;(。我尽可能多地浏览了类似的问题,但运气不佳。非常感谢!

下面程序中的两个文件都可以读取,不会出现任何错误。比较一下,看看你是否做错了什么。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile
{
public static void main(String[] args)
{
try
{
Scanner scanner = new Scanner(new File("words.txt"));
System.out.println(scanner.nextLine());
System.out.println(scanner.nextLine());
Scanner scanner2 = new Scanner(new File("C:\Users\prasad.karunagoda\words2.txt"));
System.out.println(scanner2.nextLine());
System.out.println(scanner2.nextLine());
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
}
}

最新更新