Input file not found
I just fiddled with reading input files with java until I was stumped on the simplest steps ... find the input file!
The input.txt file is in the same directory as my class file that calls it, but eclipse still gives me an error that cannot be found:
"Exception on stream" main "java.lang.Error: Unresolved compilation problem: Unhandled FileNotFoundException exception type"
My code:
package pa;
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
java.io.File file = new java.io.File("input.txt");
System.out.println(file.getAbsolutePath());
Scanner input = new Scanner(file);
}
}
input.txt is in the same package, in the same folder and in everything. I am embarrassed: (
source to share
Try using an absolute file path like:
java.io.File file = new java.io.File("C:\\My Documents\\User\\input.txt");
Also declare the method main()
like this:
public static void main(String[] args) throws FileNotFoundException {
Usually you want to catch and handle the exception, but for now, just throw it.
source to share
The "Unhandled FileNotFoundException" error can be resolved by handling exceptions in your main () method. Add the following command to your code.
public static void main(String[] args) throws FileNotFoundException
Run the program and you should get the location of the input.txt file.
You can read more about exception handling here.
Greetings
source to share