Unreported exception java.io.FileNotFoundException

2019-03-06 03:18发布

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);
          }
  }   

2条回答
放我归山
2楼-- · 2019-03-06 03:32

The constructor for Scanner you are using throws a FileNotFoundException which you must catch at compile time.

public static void main(String[] args) {

    File file1 = new File ("zips.txt");
    try (Scanner stdin = new Scanner (file1);){
        String str = stdin.next();

        System.out.println(str);
    } catch (FileNotFoundException e) {
        /* handle */
    } 
}

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 a close() call when you leave the try-catch block. You can read more about it here.

查看更多
Bombasti
3楼-- · 2019-03-06 03:40

The file is but it may not be. You either need to declare that your method may throw a FileNotFoundException, like this:

public static void main(String[] args) throws FileNotFoundException { ... }

or you need to add a try -- catch block, like this:

Scanner scanner = null;
try {
  scanner = new Scanner(file1);
catch (FileNotFoundException e) {
  // handle it here
} finally {
  if (scanner != null) scanner.close();
}
查看更多
登录 后发表回答