2012-03-20 46 views
0

誰能告訴我如何讀取多行並存儲它們的值。閱讀文件上傳中的多行

例如:file.txt的

Probable Cause: The network operator has issued an alter attribute command for 
the specified LCONF assign. The old value and the new value are show 
Action Taken : The assign value is changed from the old value to the new 
value. Receipt of this message does not guarantee that the new attribute 
value was accepted by clients who use it. Additional messages may be. 

Probable Cause: The network operator has issued an info attribute command for 
the specified LCONF assign. The default value being used is displaye 
Action Taken : None. Informational use only. 

在上面的文件,可能的原因和採取的行動是一個數據庫表中的列。在可能的原因之後:這些值是存儲在數據庫表中的可能原因列的值,與採取的操作相同。

那麼如何讀取多行並存儲它們的值呢?我必須閱讀可能的原因的值,直到該行帶有Action Taken。我正在使用BufferedReaderreadLine()方法一次讀取一行。那麼,誰能告訴我如何從可能的原因直接讀取行動,無論他們之間有多少行。

回答

1

最簡單的方法可能是隻是保持List<String>每個值,與環東西這樣的:

private static final String ACTION_TAKEN_PREFIX = "Action Taken "; 

... 

String line; 
while ((line = reader.readLine()) != null) 
{ 
    if (line.startsWith(ACTION_TAKEN_PREFIX)) 
    { 
     actions.add(line.substring(ACTION_TAKEN_PREFIX)) 
     // Keep reading the rest of the actions 
     break; 
    } 
    causes.add(line); 
} 
// Now handle the fact that either we've reached the end of the file, or we're 
// reading the actions 

一旦你得到了一個「可能的原因」 /「採取的行動」對,將字符串列表轉換回單個字符串,例如加入「\ n」,然後插入數據庫。 (該JoinerGuava將使它更容易些)

棘手位處理異常:

  • 會發生什麼事,如果你不以可能的原因開始?
  • 如果一個可能的原因之後是另一個原因,或者一個操作之後是另一個操作,會發生什麼?
  • 如果在閱讀可能的原因但沒有任何操作列表後到達文件末尾,會發生什麼情況?

我沒有現在寫了一個完整的解決的時間,但希望這些都有助於讓你去。