我得到了具有以下结构的文件:
MES2018-05-24_12:05:58.778 RGH2018-05-24_12:06:27.441 ... PGS2018-05-24_12:08:36.586
想要将其解析为 Map,其键仅包含输入字符串的前三个符号,如下所示:
MES=12:05:58.778
但是 IDE 不会编译下面提供的代码。有没有正确的方法可以使用流 API 来做到这一点?
public Map<String, Date> read(String filePath) {
SimpleDateFormat sdt = new SimpleDateFormat("HH:mm:ss.SSS");
Map<String, Date> mapFromFile = null;
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
mapFromFile = stream
.map(key -> key.split("_"))
.collect(Collectors.toMap(value -> value[0].replaceAll("[^a-zA-Z]", ""), value -> sdt.parse(value[1])));
} catch (IOException e) {
e.printStackTrace();
}
return mapFromFile;
}
最佳答案
由于您在 java 8 上使用增强功能,因此请使用 DateTimeFormatter
将 String 解析为 Localtime
并使用 LocalTime
而不是 util.Date
public Map<String, LocalTime> read(String filePath) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
return stream.map(str -> str.split("_")).collect(
Collectors.toMap(key -> key[0].substring(0, 3), val -> LocalTime.parse(val[1], formatter)));
} catch (IOException e) {
e.printStackTrace();
}
return new HashMap<>();
}
关于java - 将包含数据的文件解析为 Map<String, Date>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57966317/