未报告的异常java.io.FileNotFoundException;? [英] Unreported exception java.io.FileNotFoundException;?

查看:321
本文介绍了未报告的异常java.io.FileNotFoundException;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打开一个文件并扫描它以打印它的标记,但是我收到错误:未报告的异常java.io.FileNotFoundException;必须被捕获或声明被抛出
Scanner stdin = new Scanner(file1);该文件位于具有正确名称的同一文件夹中。

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


推荐答案

扫描程序的构造函数您正在使用抛出FileNotFoundException,您必须在编译时捕获它。

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 */
    } 
}

上面的表示法,你在括号内的 try 中声明和实例化扫描器只是Java 7中的有效表示法。这样做是做什么的离开try-catch块时,用 close()调用包装你的Scanner对象。您可以在此处了解更多相关信息。

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.

这篇关于未报告的异常java.io.FileNotFoundException;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆