0

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

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

2 回答 2

3

您正在使用的构造函数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 中的有效符号。它的作用是close()在您离开 try-catch 块时使用调用包装您的 Scanner 对象。你可以在这里阅读更多关于它的信息。

于 2013-02-08T16:57:50.103 回答
3

该文件是,但它可能不是。您要么需要声明您的方法可能会抛出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();
}
于 2013-02-08T16:58:45.757 回答