【发布时间】:2018-03-21 11:57:19
【问题描述】:
当我运行这段代码时,
public static void read_all_lines(){
String file_name = "input.txt";
File input_file = new File(file_name);
Scanner in_file = null;
try{
in_file = new Scanner(input_file);
}
catch(FileNotFoundException ex){
System.out.println("Error: This file doesn't exist");
System.exit(0);
}
while(in_file.hasNextLine()){
String line = in_file.nextLine();
System.out.println(line);
}
in_file.close();
}
这应该读取 .txt 文件中的所有行并将它们打印在抛出 FileNotFoundException 的屏幕上。它捕获它并毫无问题地打印出错误消息。但是文件确实存在,我做了两个文件input和input.txt,但是还是抛出了异常。 This is the file directory where the files and project are.
【问题讨论】:
-
您是否尝试过使用文件的完整路径,例如 "C:\\folderA\\folderB\\input.txt";
-
我会立即尝试并返回更新
-
当前工作目录是什么?
-
你能解释一下@JohannesKuhn 吗?到目前为止,我们还没有在我的课堂上提到它。如果您的意思是文件的目录,它相当长,但如果是代码,那么恐怕我还没有学会。
-
相对于您正在执行程序文件的位置,该文件位于何处?尝试将
System.out.println(System.getProperty("user.dir");添加到您的代码中,它会告诉您“工作”目录,这需要与文件所在的目录相同才能正常工作