即使文件存在,为什么也会出现“ java.nio.file.NoSuchFileException”错误?

时间:2020-07-05 02:25:41

标签: java nosuchfileexception

我收到错误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();
  }
}

2 个答案:

答案 0 :(得分:1)

我相信您的问题与您的 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 (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();
}

答案 1 :(得分:0)

只需将文本文件保留在您的项目文件夹中,然后像下面一样更改代码即可

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

相关问题