如何解决 java.nio.file.NoSuchFileException?

新手上路,请多包涵

我有一个名为“result.csv”的文件,我想从该文件中读取某些数据并显示它们。我的 Eclipse 项目文件夹本身中有该文件。我仍然无法读取文件。

  public static void main(String [] args) {
    int i=0;
    String filename="result.csv";
    Path pathToFile = Paths.get(filename);

    try (BufferedReader br = Files.newBufferedReader(pathToFile, StandardCharsets.US_ASCII)) {
        // read the first line from the text file
        String line = br.readLine();
        // loop until all lines are read
        while (i<10) {
            // use string.split to load a string array with the values from
            // each line of
            // the file, using a comma as the delimiter
            String[] attributes = line.split(",");
            double x=Double.parseDouble(attributes[8]);
            double y=Double.parseDouble(attributes[9]);
            System.out.println(GeoHash.withCharacterPrecision(x, y, 10));

            // read next line before looping
            // if end of file reached, line would be null
            line = br.readLine();
            i++;
        }
    } catch (IOException ioe) {
            ioe.printStackTrace();
    }
}

输出:

 java.nio.file.NoSuchFileException: result.csv
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.spi.FileSystemProvider.newInputStream(Unknown Source)
at java.nio.file.Files.newInputStream(Unknown Source)
at java.nio.file.Files.newBufferedReader(Unknown Source)
at com.uvce.cse.searchiot.geohash.TestGeoHash.main(TestGeoHash.java:19)

谁能指出我到底错过了什么?我该如何克服这种方法或这种方法的任何替代方法?

原文由 Snkini 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.9k
2 个回答

问题是您在应用程序启动时的默认目录不是您认为的那样。在您创建路径之后,尝试将以下行添加到您的代码中:

 public static void main(String [] args) {
    int i=0;
    String filename="result.csv";
    Path pathToFile = Paths.get(filename);
    System.out.println(pathToFile.toAbsolutePath());

这样,您将准确地看到它在哪里寻找文件。

如何解决它是您的决定。您可以使用完整路径规范而不仅仅是文件名,或者将文件名放在特殊的“资源”目录中并使用相对路径引用它,或者将文件移动到默认目录所在的任何位置。

原文由 DodgyCodeException 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果你的 file("result.csv") 在 src 目录中,你应该使用 “src/result.csv” 而不是 “result.csv”

原文由 Stackoverflow 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题