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

mfuanj7w  于 2021-08-25  发布在  Java
关注(0)|答案(4)|浏览(2280)

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

  1. public static void main(String [] args) {
  2. int i=0;
  3. String filename="result.csv";
  4. Path pathToFile = Paths.get(filename);
  5. try (BufferedReader br = Files.newBufferedReader(pathToFile, StandardCharsets.US_ASCII)) {
  6. // read the first line from the text file
  7. String line = br.readLine();
  8. // loop until all lines are read
  9. while (i<10) {
  10. // use string.split to load a string array with the values from
  11. // each line of
  12. // the file, using a comma as the delimiter
  13. String[] attributes = line.split(",");
  14. double x=Double.parseDouble(attributes[8]);
  15. double y=Double.parseDouble(attributes[9]);
  16. System.out.println(GeoHash.withCharacterPrecision(x, y, 10));
  17. // read next line before looping
  18. // if end of file reached, line would be null
  19. line = br.readLine();
  20. i++;
  21. }
  22. } catch (IOException ioe) {
  23. ioe.printStackTrace();
  24. }
  25. }

输出:

  1. java.nio.file.NoSuchFileException: result.csv
  2. at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
  3. at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
  4. at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
  5. at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
  6. at java.nio.file.Files.newByteChannel(Unknown Source)
  7. at java.nio.file.Files.newByteChannel(Unknown Source)
  8. at java.nio.file.spi.FileSystemProvider.newInputStream(Unknown Source)
  9. at java.nio.file.Files.newInputStream(Unknown Source)
  10. at java.nio.file.Files.newBufferedReader(Unknown Source)
  11. at com.uvce.cse.searchiot.geohash.TestGeoHash.main(TestGeoHash.java:19)

有人能指出我到底错过了什么吗?我怎样才能克服这个问题,或者用其他方法来解决这个问题呢?

ffvjumwh

ffvjumwh1#

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

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

这样,您就可以确切地看到它在哪里查找文件。
如何修复它是你的决定。您可以使用完整路径规范,而不仅仅是文件名,或者将文件名放在特殊的“资源”目录中,并使用相对路径引用它,或者将文件移动到默认目录所在的位置。

7uzetpgm

7uzetpgm2#

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

9q78igpj

9q78igpj3#

问题是java无法在项目文件夹中找到“result.csv”文件。因此,尝试使用文件的完全限定路径,例如。 C:\your_folder\project\result.csv 在path变量中。此外,我认为最好像这样使用bufferedreader: BufferedReader br = new BufferedReader(new FileReader(insert here the String in which is defined the path to the file)); 在此处检查bufferedreader的用法

bvuwiixz

bvuwiixz4#

如果您是macosx用户,请手动键入文件路径,而不是从“获取信息”复制文件路径。如果您从“获取信息”中复制它,您将得到类似的结果:/users/username<200e><2068><2068>/desktop<2069>/source.txt

相关问题