【问题标题】:Can't read txt file with Scanner in Eclipse (Java)无法在 Eclipse (Java) 中使用 Scanner 读取 txt 文件
【发布时间】:2018-12-17 11:37:24
【问题描述】:

我在 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。有人对此有任何见解吗?我知道文件在那里;我还缺少什么?我相信我也有正确的进口(@98​​7654326@ 和import java.util.Scanner;)。我浏览了尽可能多的类似问题,但没有运气。非常感谢!

【问题讨论】:

  • FileNotFoundException 究竟是什么意思?
  • 您已经测试该程序是否有权访问这些文件?
  • 请提供System.out.println(wordsPath2) 的输出,以及您获得异常的确切行。我怀疑它可能在wordsPath2 中丢失了\\Documents,例如String wordsPath2 = workingDir.concat("\\Documents\\words.txt");
  • 复制文件后,您是否尝试刷新(右键单击 -> 刷新)项目文件夹?这将使您的文件系统与 Eclipse 的内部文件系统同步。
  • 显然编译器需要一个 try/catch 块,我什至无法尝试运行它,因为我没有捕捉到它。我不知道它有那么严格,但我很抱歉没有早点尝试。

标签: java eclipse java.util.scanner java-io filenotfoundexception


【解决方案1】:

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

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

【讨论】:

  • 它最终成为了 try/catch 语句。编译器出于某种原因需要它。谢谢。
猜你喜欢
  • 2023-03-15
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多