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

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

我有一个名为“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)

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

ffvjumwh

ffvjumwh1#

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

public static void main(String [] args) {
    int i=0;
    String filename="result.csv";
    Path pathToFile = Paths.get(filename);
    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

相关问题