2013-05-19 43 views
1

我有一個任務,我需要編寫一個包含try­catch語句的while循環代碼塊。 try塊從輸入文件中檢索每一行,並調用我創建的isValid方法來檢查格式是否正確,並將該行傳遞給文件。如果沒有更多行要解析,runProgram設置爲false,則while循環終止。 catch塊會捕獲我所做的例外。到目前爲止,我有錯誤捕獲和文件IO

public static void main(String[] args) 
    { 
    File file; 
    Scanner inputFile; 
    String fileName; 

    Scanner scan = new Scanner(file); 
    fileName = scan.nextLine(); 

    boolean runProgram = true; 
    while(runProgram) 
    { 
     try 
     { 
      // for loop to check each line of my file 
      // invoke isValid 
      // Check if it's the last line in the file, and end program if so 
     } 
     catch(BankAccountException e) 
     { 
      System.out.println("Account Exception. Do you wish to quit? y/n"); 
      String quit = scan.nextLine(); 
      if(quit.equals("y")) 
       runProgram = false; 
      else 
       runProgram = true; 
     } 
    } 
    } 

我只是不知道如何打開一個文件,檢查下一行,用我isValid方法(這僅僅是一個StringTokenizer是正確的格式檢查),當它到達關閉文件的結尾。

這裏是我isValid方法:

private static boolean isValid(String accountLine) throws BankAccountException 
    { 
     StringTokenizer strTok = new StringTokenizer(accountLine, ";"); 
     boolean valid = true; 
     if(strTok.countTokens() == 2) 
     { 
     if(strTok.nextToken().length() == 10) 
     { 
      if(!strTok.nextToken().matches(".*[0-9].*")) 
      { 
       valid = true; 
      } 
     } 
     } 
     else 
     valid = false; 
     return valid; 
    } 

我也有上述方法的問題。如果我撥打.nextToken()兩次,我是否期待第一個迭代處理第一個標記,第二個處理第二個標記呢?或者他們都會檢查第一個標記?

+0

看[文件](http://docs.oracle.com/javase/6/docs/api/java/io/File.html),[的FileReader](http://docs.oracle .com/javase/6/docs/api/java/io/FileReader.html)和[BufferedReader](http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html) 。他們應該能夠實現你想要的。否則,探索IO包。 [教程](http://docs.oracle.com/javase/tutorial/essential/io/)也很有用。 – BevynQ

回答

0

只是爲了讓你開始。

try { 
    BufferedReader reader = new BufferedReader(new FileReader(new File("/path/to/File"))); 
    String currLine; 
    while ((currLine = reader.readLine()) != null) { // returns null at EOF 
     if (!isValid(currLine)) throw new BankAccountException(); 
    } 
} catch (BankAccountException e) { 
    // same 
} finally { 
    reader.close(); 
}