Unreported exception java.io.FileNotFoundException;?

北城余情 提交于 2019-12-02 17:35:44

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/14777511/unreported-exception-java-io-filenotfoundexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!