未报告的exceptionjava.io.FileNotFoundException;?

我想打开一个文件并扫描它来打印它的令牌,但我收到错误:未报告的exceptionjava.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); } } 

您正在使用的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声明和实例化扫描器只是Java 7中的有效表示法。这样做是当你离开try-catch块时用close()调用包装你的Scanner对象。 你可以在这里阅读更多相关信息。

该文件但可能不是。 您需要声明您的方法可能抛出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(); }