如何解决java.nio.file.NoSuchFileException?
我有一个名为“result.csv”的文件,我想从该文件中读取某些数据并显示它们。我的eclipse项目文件夹中有这个文件。我仍然无法读取文件如何解决java.nio.file.NoSuchFileException?,java,file,Java,File,我有一个名为“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.newBuffer
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();
}
}
有人能指出我到底错过了什么吗?我该如何克服这种方法或这种方法的任何替代方法呢?问题在于,应用程序启动时的默认目录与您想象的不同。创建路径后,尝试将以下行添加到代码中:
public static void main(String [] args) {
int i=0;
String filename="result.csv";
Path pathToFile = Paths.get(filename);
System.out.println(pathToFile.toAbsolutePath());
这样,您就可以确切地看到它在哪里查找文件
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无法在项目文件夹中找到“result.csv”文件。因此,请尝试使用文件的完全限定路径,例如路径变量中的
C:\your\u folder\project\result.csv
。另外,我认为最好像这样使用bufferedreader:bufferedreader br=new bufferedreader(new FileReader(在这里插入定义文件路径的字符串))
检查BufferedReader的使用情况如果您的文件(“result.csv”)
位于src目录中,则应使用“src/result.csv”而不是“result.csv”如果您是MacOSX用户,请手动键入文件路径,而不是从“获取信息”复制文件路径。
如果您从“获取信息”复制它,您将得到类似的内容:
/Users/username/Desktop/source.txt您正在使用Maven项目吗?问题是文件不在类路径上,因此当您运行程序时,Java找不到该文件。一种解决方法是只使用文件的完全限定路径,例如
C:\your\u folder\project\result.csv
。另一种方法是从类路径加载它。问题使用硬编码的文件名,所以这不是问题。Java.nio.file.path
没有getAbsolutePath()
方法。谢谢,绝对路径的东西真的帮助我找到了它在系统中的位置。最简单的解决方案!