I want to open a file and scan it to print its tokens but I get the error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner stdin = new Scanner (file1); The file is in the same folder with the proper name.
import java.util.Scanner;
import java.io.File;
public class myzips {
public static void main(String[] args) {
File file1 = new File ("zips.txt");
Scanner stdin = new Scanner (file1);
String str = stdin.next();
System.out.println(str);
}
}
The constructor for
Scanner
you are using throws a FileNotFoundException which you must catch at compile time.The above notation, where you declare and instantiate the Scanner inside the
try
within parentheses is only valid notation in Java 7. What this does is wrap your Scanner object with aclose()
call when you leave the try-catch block. You can read more about it here.The file is but it may not be. You either need to declare that your method may throw a
FileNotFoundException
, like this:or you need to add a
try -- catch
block, like this: