我有以下一行
STATUS | webapp | 2014/05/26 15:03:13 | Starting the service...
现在我必须从行中提取小时分钟和秒钟。
我想出了这段代码..
BufferedReader bin = new BufferedReader(new FileReader(wrapperFile));
s = bin.readLine();
final Scanner sc = new Scanner(s);
final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
while (sc.hasNextLine()) {
final String line = sc.nextLine();
final Date date = dateFormat.parse(line);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.print(calendar.get(Calendar.HOUR));
System.out.print(calendar.get(Calendar.MINUTE));
System.out.print(calendar.get(Calendar.SECOND));
}
但抛出了解析器异常..这个问题是否有解决方法.. ??
答案 0 :(得分:3)
([0-9]{2}:){2}[0-9]{2}
将匹配HH:MM:SS
答案 1 :(得分:2)
完整的解决方案:
String input = "STATUS | webapp | 2014/05/26 15:03:13 | Starting the service...";
String[] splitted = input.split("\\s\\|\\s");
String dateTime = splitted[2];
Calendar c = Calendar.getInstance();
try {
Date d = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(dateTime);
c.setTime(d);
System.out.println("Year: " + c.get(Calendar.YEAR));
System.out.println("Month: " + c.get(Calendar.MONTH));
System.out.println("Day in month: " + c.get(Calendar.DAY_OF_MONTH));
System.out.println("Hour: " + c.get(Calendar.HOUR_OF_DAY));
System.out.println("Minute: " + c.get(Calendar.MINUTE));
System.out.println("Second: " + c.get(Calendar.SECOND));
}
catch (Throwable t) {
// test
t.printStackTrace();
}
<强>输出强>
Year: 2014
Month: 4 // 0-based!
Day in month: 26
Hour: 15
Minute: 3
Second: 13
答案 2 :(得分:1)
使用String
分隔符拆分输入|
,然后在{Lin> rd 数组元素上使用带有模式SimpleDateFormat
的{{1}} { {1}}