【问题标题】:Reading a file in Java with Scanner使用 Scanner 读取 Java 文件
【发布时间】:2017-01-18 12:10:09
【问题描述】:

我正在尝试让程序读取文本文件,但它会抛出 FileNotFoundException,即使我在项目目录中设置了 potato.txt 文件。

import java.io.File;
import java.util.Scanner;

public static void main(String[] args) {
    String potato = "potato.txt"; // assume this line can't be changed at all

    Scanner scan = new Scanner(new File(potato)); // throws FileNotFoundException

    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        System.out.println(line);
    }


}

}

【问题讨论】:

  • 你的文件到底在哪里?
  • 尝试使用绝对路径。
  • 请发布项目结构

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


【解决方案1】:

尝试使用完整路径,如下所示:

File file = new File("C:/temp/potato.txt"); //This is just an example path, look up your files path and put it here.
Scanner scan = new Scanner(file);

另外,完成后不要忘记关闭扫描仪(在您的while-loop 之后):

scan.close();

【讨论】:

  • 我已经这样设置并将文件路径设置为(“C:/Users/The Turd 9000/workspace/IOTutorial/potato.txt”)。我是通过使用 getabsolutepath(); 得到的。它仍然在 Scanner 行上给我相同的 FileNotFoundException。
  • 编辑你的项目结构和你的问题中的完整错误信息,所以我可以看看。
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 2021-01-04
  • 1970-01-01
  • 2013-11-11
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
相关资源
最近更新 更多