我正在阅读日志文件,需要从某些行中提取日期和年份,然后使用简单的日期格式,找出两次操作之间的平均时间。我需要日期的行的示例如下所示。
(INFO ) [07 Feb 2013 08:04:39,161] -- ua, navigation, fault
我无法弄清楚是否应该将线分割两次或使用子串函数。转换为简单的日期格式(161)时,我认为我不需要包含最后一个数字。
答案 0 :(得分:1)
我建议你使用正则表达式从日志文件中提取所需的数据。
答案 1 :(得分:0)
我会去使用子字符串:
final int from = line.indexOf('[') + 1;
final int to = line.indexOf(']', from); // or , if you do not want to have the last number included
final String timestampAsString = line.substring(from, to);
顺便说一句:如果找到了有效的索引,则添加一些from / to-checks - 例如,在日志格式发生变化时及早发现错误。
答案 2 :(得分:0)
考虑使用正则表达式组来提取所需的字符串。你可以使用
Pattern p = Pattern.compile("you regex pattern with () around the bit you wanna extract");
Matcher m = p.matcher(theLine);
if (m.find()) {
String date = m.group(1);
}