2013-03-10 18 views
1

我在閱讀.dat文件時遇到了問題。 目前,我知道如何讀取.dat/.txt文件,但這對我來說有點棘手。在文件中循環,按行設置一組行

所以我有這樣一組數據:

TEST.DAT

Sunday 
Scuba Diving Classes 
Mr.Jones 
N/A 
Yes 

Sunday 
Sailing 
Mr. Jackson 
N/A 
Yes 

Sunday 
Generation Next 
Ms.Steele 
N/A 
Yes 

Monday 
Helping Hands 
Ms.Wafa 
ANX0 
No 

我需要這個文件做的是去通過記錄文件記錄,如果一個字符串activityname .equals到活動的名稱(例如水肺潛水課程),以C開頭的變量被設置爲查看。下面是它的編碼:

try{ 
      BufferedReader reader = new BufferedReader(new FileReader("test.dat")); 

       int numberOfLines = readLines(); 
       numberOfLines = numberOfLines/6; 

       for(int i=0;i < numberOfLines; i++) 
       { 
        String CDay = reader.readLine(); 
        String CActivityName = reader.readLine(); 
        String CSupervisor = reader.readLine(); 
        String CLocation = reader.readLine(); 
        String CPaid = reader.readLine(); 
        String nothing = reader.readLine(); 

        if(CActivityName.equals(activityName)) 
        { 
         txtDay.setText(CDay); 
         txtSupervisor.setText(CSupervisor); 
         txtLocation.setText(CLocation); 

         //If it Activity is paid, then it is shown as paid via radiobutton 
         if(CPaid.equals("Yes")) 
           { 
            radioYes.setSelected(rootPaneCheckingEnabled); 
           } 
         if(CPaid.equals("No")) 
           { 
            radioNo.setSelected(rootPaneCheckingEnabled); 
           } 
        } 
        else 
        { 
         reader.close(); 
        } 
       } 
     } 
     catch(IOException e) 
     { 
       Logger.getLogger(AddActivity.class.getName()).log(Level.SEVERE, null, e); 
     } 
    } 

我使用numberoflines變量要經過該文件,但我的邏輯是有缺陷的,我不知道如何去通過這個

現狀和方法

的誤差目前,這種方法只讀取第一個記錄水肺潛水學校,當如果條件爲假不通過整個文件去。

幫助!

+2

你一旦遇到名稱不等於activityName的活動,請關閉閱讀器。別。 – 2013-03-10 17:50:56

+0

這工作!沒有看到我的邏輯缺陷 謝謝! – Geuni 2013-03-10 17:55:29

回答

2

當前,當if條件爲false時,此方法...不經過整個文件。

找出原因,採取一看else塊:

else 
{ 
    reader.close(); 
} 

這意味着你關閉BufferedReader你讀完該文件之前。你不需要在else塊中放置任何東西。

+0

JB Nizet在一分鐘前給了我答案,但還是,謝謝你+清楚的解釋! – Geuni 2013-03-10 18:00:26

1

我看到JB Net評論幫了你。此外,在一般你應該關閉的一個IO變量(文件,數據或其他)finally塊,像這樣:

InputStream is = null; 
try{ 
    //open streams, do work 
}catch(...){ 

}finally{ 
//seperate try catch here to make sure it does not affect anything else, just close one resource per try catch 
try{ 
    if(is != null){ 
     is.close() 
    }catch(Exception ...){ 
     //one line log 
    } 
} 

在Java 7中你必須嘗試用資源,但沒有試過:)

+0

是否有未來的錯誤的finally塊不存在的可能性?對不起,我是新來的,不太熟悉最後的塊... – Geuni 2013-03-10 18:10:04

+1

不知道我理解你。你是否問過如果你不使用finally塊會有錯誤?如果是的話 - 最終可能會導致程序運行時無法寫入的文件或程序耗盡套接字和其他句柄。在迭代處理/服務器應用程序中更重要 – tgkprog 2013-03-10 20:34:15