【发布时间】:2026-02-18 09:20:04
【问题描述】:
我只是想制作一个非常基本的 java 程序来读取文件。但是我得到它找不到我的文件的错误:
Exception in thread "main" java.io.FileNotFoundException: read.txt (The system cannot find the file specified)
我查了一下,我的文件名没有拼错,而且文件已经和程序在同一个文件目录下。
代码如下:
import java.io.*;
import java.util.*;
public class save_files {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("read.txt");
Scanner scanner = new Scanner(file);
String line = scanner.nextLine();
System.out.println(line);
}
}
【问题讨论】:
-
将文件放在项目根文件夹中以使其工作。
-
尝试将文本文件的完整路径放在那里,看看您的代码是否有效。 :)
-
@SureshAtta 根文件夹是什么意思?
-
@arcanium0611 是的,谢谢你的工作,但是有没有更简单的方法可以做到这一点,因为我也在 python 中编码并且知道如果它在同一个文件目录中,你只需要放置文件
-
如果您在 eclipse 或 intelliJ 中工作,请尝试通过 IDE 将文件添加到您的项目中。这通常对我有用。
标签: java