[英]Java - Reading text file
我有一個文本文件,如下所示:
Past Dues / Refunds / Subsidy
Arrears / Refunds
Amount
2013.23
Period to which
it relates
Since OCT-15
現在,如何提取“金額”下一行中的數據。 我已經嘗試過使用布爾值,檢查上面和下面的行。
還有其他方法可以做到這一點。
我的代碼:
boolean isGroup=false;
while(line = br.readline() != null){
if(line.equals("Amount"){
isGroup=true;
}
if(line.equals("Period to which") && isGroup)
isGroup=false;
if(isGroup){
//read line and check whether it is null or not
String amount = line;
}
}
請幫忙。 謝謝
您的方法非常好。 通過設置布爾值,然后在循環的同一迭代中使用,您犯了一個小錯誤。
如果您執行以下操作,就可以了:
String amount = "No amount found";
boolean isGroup=false;
while(line = br.readline() != null) {
// Check all your conditions to see if this is the line you care about
if(isGroup){
amount = line;
isGroup = false; // so you only capture this once
continue;
}
else if (isOtherCondition) {
// handle other condition;
isOtherCondition = false; // so you only capture this once
continue;
}
// Check the contents of lines to see if it's one you want to read next iteration
if(line.equals("Amount"){
isGroup=true;
}
else if (line.equals("Some Other Condition")) {
isOtherCondition = true;
}
}
這就是您所需要的。 break;
只是這樣,您不必擔心在獲取金額后會發生什么。
如果文件是平均大小,則可以使用正則表達式。
只需將整個文件讀入字符串即可。
要使用正則表達式將是這樣的。
結果在捕獲組1中。
"(?mi)^\\\\s*Amount\\\\s+^\\\\s*(\\\\d+(?:\\\\.\\\\d*)?|\\\\.\\\\d+)\\\\s*$"
(?mi) # Multi-line mode, case insensitive
^ # Beginning of line
\s* Amount \s+
^ # Beginning of line
\s*
( # (1 start), Numeric value
\d+
(?: \. \d* )?
| \. \d+
) # (1 end)
\s*
$ # End of line
這就是你在Java中做@sln答案的方式
String text = "Past Dues / Refunds / Subsidy\n" +
"Arrears / Refunds\n" +
"Amount\n" +
"2013.23\n" +
"Period to which\n" +
"it relates\n" +
"Since OCT-15";
Pattern pattern = Pattern.compile("(?mi)^Amount\\s(?<amount>\\d+\\.\\d{2})");
Matcher matcher = pattern.matcher(text);
if(matcher.find()){
String amount = matcher.group("amount");
System.out.println("amount: "+ amount);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.