[英]How to solve the 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();
}
}
OUTPUT:
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)
谁能指出我到底错过了什么? 我该如何克服这种方法或这种方法的任何替代方法?
问题是您在应用程序启动时的默认目录不是您认为的那样。 在创建路径之后,尝试将以下行添加到您的代码中:
public static void main(String [] args) {
int i=0;
String filename="result.csv";
Path pathToFile = Paths.get(filename);
System.out.println(pathToFile.toAbsolutePath());
这样,您将准确地看到它正在寻找文件的位置。
如何修复它是您的决定。 您可以使用完整路径规范而不仅仅是文件名,或者将文件名放在特殊的“资源”目录中并使用相对路径引用它,或者将文件移动到默认目录所在的任何位置。
如果您的file("result.csv")
在 src 目录中,您应该使用“src/result.csv”而不是“result.csv” 。
问题在于 java 无法在项目文件夹中找到“result.csv”文件。 因此,尝试使用文件的完全限定路径,例如 Path 变量中的C:\\your_folder\\project\\result.csv
。 另外我认为最好像这样使用bufferedreader: BufferedReader br = new BufferedReader(new FileReader(insert here the String in which is defined the path to the file));
在此处检查 BufferedReader 的使用
如果您是 MacOSX 用户,请手动输入文件路径,而不是从“获取信息”中复制。 如果你从“获取信息”中复制它,你会得到这样的东西: /Users/username<200e><2068><2068>/Desktop<2069>/source.txt
我遇到了由 Windows 文件路径上的转义字符引起的相同错误。 例如,我的应用程序正在寻找“ C:\\Users\\david\\my%20folder%20name\\source.txt
”,而实际路径是“ C:\\Users\\david\\my folder name\\source.txt
”。
这里不舍弃所有可能的解决方案,当您在 Windows 环境下运行 Android Studio 并使用非 NFTS 格式的外部硬盘驱动器上的项目目录时,也会出现此错误。 ]
如果是这种情况,只需将您的项目移动到主硬盘 (NTFS) 并再次重新加载项目,这次是从主硬盘文件夹路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.