我的阅读程序会吐出"FileNotFound"异常,有什么想法吗?
代码片段:
import java.io.FileReader;
import java.io.BufferedReader;
public class Main{
public static void main (String [] args){
try{
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String[] input = new String[0];
String[] temp = new String[1];
for (int i = 0; (br.readLine()) != null; i++){
for(int j = 0; j < (i); j++){
temp[j] = input[j];
}
temp[i] = br.readLine();
input = new String [i + 1];
for(int j = 0; j <= (i); j++){
input[j] = temp[j];
}
temp = new String[i + 2];
}
br.close();
} catch (IOException error1){
System.out.println("Error 404: File Not Found");
}
}
现在代码是可编译的,但吐出"错误 404:找不到文件",尽管"file.txt"与"class"文件位于同一文件夹中。为什么?
在创建 BufferedReader 之前添加以下语句
System.out.println(new File(args[0]).getAbsolutePath());
并检查输出的路径是否实际指向文件系统上的现有文件。
说,因为您没有提供文件的路径或任何东西,但请尝试使用文件的绝对路径。
假设您有一个这样的文件结构
C:/
My_IDE_Projex
ProjectRoot
bin
Main.class
src
Main.java
如果您从命令行使用实路径"myFile.txt",如果您从命令行编译了 java 文件,无论您在哪里指定要编译的类文件,都需要该文件。例如:
C:My_IDE_ProjexProjectRootbin> java Main myFile.txt
文件应位于 bin 文件夹中