[英]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.