Java 使用绝对路径时找不到文件
每次我给FileReader提供完整的文件路径时,都会遇到FileNotFoundException。但是,只要在复制程序所在的同一目录中的文件后给出文件名,程序就可以正常执行Java 使用绝对路径时找不到文件,java,filereader,Java,Filereader,每次我给FileReader提供完整的文件路径时,都会遇到FileNotFoundException。但是,只要在复制程序所在的同一目录中的文件后给出文件名,程序就可以正常执行 // Doesn't work FileReader in = new FileReader(files_path +"\\"+ "fileName.csv"); Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in); for
// Doesn't work
FileReader in = new FileReader(files_path +"\\"+ "fileName.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records)
{
System.out.println(record.get(7));
}
//Works
FileReader in = new FileReader("fileName.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records)
{
System.out.println(record.get(7));
}
//不起作用
FileReader in=新的FileReader(文件路径+“\\”+“fileName.csv”);
Iterable records=CSVFormat.EXCEL.parse(in);
用于(CSVRecord记录:记录)
{
System.out.println(record.get(7));
}
//工作
FileReader in=新的FileReader(“fileName.csv”);
Iterable records=CSVFormat.EXCEL.parse(in);
用于(CSVRecord记录:记录)
{
System.out.println(record.get(7));
}
由
files_path +"\\"+ "fileName.csv"
不存在。这就是您遇到此错误的原因
潜在原因:
表示无效或不存在的路径文件\u路径
本身以反斜杠结束(尽管这不会在Windows上造成那么多问题)files\u路径
- 您不在Windows上,在这种情况下,您需要使用正斜杠作为文件分隔符。正如注释中已经建议的,使用Java常量
独立于平台File.separator
FileReader
构造函数之前,您应该将整个路径存储到字符串变量中,并将其打印到System.out
。然后,您可以轻松地验证这是否是有效路径。在Windows上,请尝试用File.separator
替换路径中的前斜杠。