Unreported exception java.io.FileNotFoundException;?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 07:49:58

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.

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