【问题标题】:Unreported exception java.io.FileNotFoundException;?未报告的异常 java.io.FileNotFoundException;?
【发布时间】:2014-07-20 23:10:53
【问题描述】:

我想打开一个文件并扫描它以打印其令牌,但我收到错误:未报告的异常 java.io.FileNotFoundException;必须被抓住或宣布被抛出 扫描仪标准输入 = 新扫描仪(文件 1);该文件位于具有正确名称的同一文件夹中。

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

【问题讨论】:

    标签: java file io java.util.scanner


    【解决方案1】:

    您正在使用的Scanner 的构造函数抛出一个 FileNotFoundException,您必须在编译时捕获它。

    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 内声明和实例化 Scanner 只是 Java 7 中的有效符号。它的作用是在您离开 try-catch 时使用 close() 调用包装您的 Scanner 对象堵塞。你可以阅读更多关于它的信息here

    【讨论】:

    • 我认为重要的是要补充一点,这个try - catch 表示法仅在SDK7 及以上版本中有效。它还处理扫描仪上的close 操作。
    • 好主意,我添加了一个链接,您可以在其中阅读有关 JAVA 7 中语言更改的更多信息。
    【解决方案2】:

    文件是,但它可能不是。你要么需要声明你的方法可能会抛出一个FileNotFoundException,像这样:

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

    或者你需要添加一个try -- catch 块,像这样:

    Scanner scanner = null;
    try {
      scanner = new Scanner(file1);
    catch (FileNotFoundException e) {
      // handle it here
    } finally {
      if (scanner != null) scanner.close();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多