2013-02-08 227 views
0

我想打开一个文件并对其进行扫描以打印它的标记,但出现错误:未引发异常java.io.FileNotFoundException;必须被捕获或宣布被抛出 扫描仪标准输入=新扫描仪(文件1);该文件与正确的名称在同一个文件夹中。未报告的异常java.io.FileNotFoundException ;?

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

回答

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内扫描仪仅在Java 7中这样做是有close()呼叫包裹扫描器对象中的有效符号当你离开的try-catch块。你可以阅读更多关于它here

+0

我认为,重要的是要补充一点,这个'try-catch'符号只在'SDK7'及以上版本中有效。它还处理扫描仪上的“关闭”操作。 – Michael 2013-02-08 17:13:56

+0

好主意,我已经添加了一个链接,你可以在这里阅读更多关于JAVA 7语言变化的链接。 – 2013-02-08 17:18:30

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(); 
} 
相关问题