Java: 找不到文件异常

Java: file not found exception

File file1 = new File("news1.txt");
System.out.println(file1.exists());

这会打印 false,但是文件 news1.txt 在目录中,其中 class.

这假定 news1.txt 与 class 在同一文件夹中,调用此代码。例如,如果您使用的是 Eclipse,这将在项目的根文件夹中查找文件,而不是在 src 文件夹中。您应该验证该文件确实位于正确的位置。

我通常会尝试从 class 读取的位置获取文件夹。通过在光盘上写入一个测试文件并查看它的创建位置,可以很容易地做到这一点。你可以这样做:

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

现在您知道默认目录在哪里,这样您就可以导航到您的文件或将文件放在正确的位置