Reputation: 21
When I run this code,
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();
}
That is supposed to read all lines in a .txt file and print them on the screen the FileNotFoundException is thrown. It catches it and prints out the error message with no problem. But the file does exist, I made two files input and input.txt, but the exception is still thrown. This is the file directory where the files and project are.
Upvotes: 0
Views: 65
Reputation: 2442
From the looks of it, the program seems to be in the folder "Guided Exercise 4" where the text files are outside that folder. If this is the case then either move the text files into the same folder as the program or File input_file = new File("..\\" + file_name);
to reference the file in the parent directory. But I would recommend the moving the text files.
Upvotes: 1
Reputation: 21
The files were not in the right area. Using System.out.println(System.getProperty("user.dir"));
given by MadProgrammer I found what directory the program needed the files in and corrected the issue
Upvotes: 1