首页 > 解决方案 > 无法在 Eclipse (Java) 中使用 Scanner 读取 txt 文件

问题描述

我在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;)我也有正确的进口。我浏览了尽可能多的类似问题,但没有运气。非常感谢!

标签: javaeclipsejava.util.scannerjava-iofilenotfoundexception

解决方案


下面程序中的两个文件都可以毫无错误地读取。比较一下,看看你是否做错了什么。

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();
    }
  }
}

推荐阅读