Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 提取要以简单日期格式使用的子字符串_Java_Hashmap_Indexof - Fatal编程技术网

Java 提取要以简单日期格式使用的子字符串

Java 提取要以简单日期格式使用的子字符串,java,hashmap,indexof,Java,Hashmap,Indexof,我正在读取日志文件,需要从某些行中提取日期和年份,以便使用简单的日期格式并找出两个操作之间的平均时间。我需要日期的行的示例如下所示 (INFO ) [07 Feb 2013 08:04:39,161] -- ua, navigation, fault 我不知道是应该将行拆分两次还是使用substring函数。此外,我认为在转换为简单日期格式(161)时不需要包含最后一个数字。我会选择使用子字符串: final int from = line.indexOf('[') + 1; final in

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

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

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

我会选择使用子字符串:

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检查是否找到了有效索引-例如,在日志格式更改时早期检测错误。

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

考虑使用正则表达式组提取所需的字符串。你可以用

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);
}

161是毫秒。如果您已经拥有它,也许您可以使用它…如果
[
不可用,您可能会获得
索引自动边界异常。