【问题标题】:Why do I get an "java.nio.file.NoSuchFileException" error even though the file exists?为什么即使文件存在,我也会收到“java.nio.file.NoSuchFileException”错误?
【发布时间】:2020-10-25 09:45:09
【问题描述】:

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

【问题讨论】:

  • "no such file" 错误提示您尝试使用的文件不存在。你觉得有吗?
  • VSC 和 Elipse IDE 都出现过,我昨天刚下载。如何配置它
  • Umm ...在文件系统中查看“C:\\Users\\Admin\\Desktop\\Java.txt”是否有文件。如果它不存在 在那个位置 ...这就是您的应用程序找不到它的原因!可能的解决方案:1)创建文件,或 2)更正程序中的路径。
  • 我有检查器,并且我之前已经插入了确切的地址文件。但是还是报错
  • 好的,我误会了一个无法用语言解释的问题。无论如何非常感谢你

标签: java nosuchfileexception


【解决方案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 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();
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 2021-12-30
      • 2019-10-11
      • 2022-11-03
      • 2022-06-10
      • 2021-08-21
      相关资源
      最近更新 更多