问题
I am a Java beginner and have read similar questions but still I dont get why my code is showing a FileNotFound Exception. My file is in the same directory.
My code is:
import java.io.*;
import java.util.Scanner;
public class reader {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
double y = in.nextDouble();
float g = in.nextFloat();
String a = in.next();
File file = new File("v.txt");
System.out.println(x + "" + y + "" + g + "" + a);
Scanner inFile = new Scanner(new FileReader(file));
String u = inFile.nextLine();
System.out.println(file.getAbsolutePath());
System.out.println(u);
}
}
Error is:
17: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Scanner inFile = new Scanner(new FileReader(file));
^
1 error
回答1:
You are encountering a compile time error:
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Scanner inFile = new Scanner(new FileReader(file));
This is a simple way of fixing it:
public class reader {
public static void main(String[] args) throws Exception {
//...
}
}
although using try {...} catch(...){ } is a better way of dealing with the possible run time exception.
来源:https://stackoverflow.com/questions/27756407/reading-a-file-using-filereader-and-scanner