0

我收到错误消息Exception in thread "main" java.nio.file.NoSuchFileException,但我确定该文件存在于给定位置C:\\Users\\Admin\\Desktop\\Java.txt"

为什么我仍然会收到此错误?

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Scanner;

public class ReadData {
  public static void main(String[] args) throws IOException {
        
    Scanner file = new Scanner(Paths.get("C:\\Users\\Admin\\Desktop\\Java.txt", "UTF-8"));
    int int_value;
    while ((file.hasNextInt())) {
        int_value = file.nextInt();
        System.out.println("Data:" + int_value);
    }

    file.close();
  }
}
4

2 回答 2

3

我相信您的问题在于您的Paths.get()方法:

Scanner file = new Scanner(Paths.get("C:\\Users\\Admin\\Desktop\\Java.txt", "UTF-8"));

Paths.get()方法的右括号在错误的位置。您实际提供给 Scanner 对象的内容(或 get() 方法将其解释为的内容)是这样的路径:

"C:\Users\Admin\Desktop\Java.txt\UTF-8"

显然找不到那个特定的路径。它应该是:

Scanner file = new Scanner(Paths.get("C:\\Users\\Admin\\Desktop\\Java.txt"), "UTF-8");

您可能还想考虑使用Try With Resources机制。它将自动关闭文件阅读器:

try (Scanner file = new Scanner(Paths.get("C:\\Users\\Admin\\Desktop\\Java.txt"), "UTF-8")) {
    int int_value;
    while ((file.hasNextInt())) {
        int_value = file.nextInt();
        System.out.println("Data:" + int_value);
    }
}
catch (IOException ex) {
    ex.printStackTrace();
}
于 2020-07-05T07:44:21.430 回答
0

只需将文本文件保存在您的项目文件夹中,只需更改如下代码

Scanner file=new Scanner(new File("Java.txt")); 希望它能解决你的问题

于 2020-07-05T07:20:58.323 回答