2013-02-08 225 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(); 
} 
相關問題