0

我正在阅读日志文件,需要从某些行中提取日期和年份,以便使用简单的日期格式并找出两个操作之间的平均时间。我需要日期的行的示例如下所示。

(INFO ) [07 Feb 2013 08:04:39,161] -- ua, navigation, fault

我不知道是否应该将该行拆分两次或使用 substring 函数。此外,我认为在转换为简单日期格式(161)时不需要包含最后一个数字。

4

3 回答 3

1

我建议您使用正则表达式从日志文件中提取所需的数据。

于 2013-03-14T13:47:36.390 回答
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);

顺便说一句:如果找到有效索引,请添加一些从/到检查 - 例如,在日志格式更改时及早检测错误。

于 2013-03-14T13:43:53.630 回答
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);
}
于 2013-03-14T13:56:37.330 回答