我有一个文本文件,每15-16分钟更新一些json数据。这些json数据由中间的####行分隔。该文件的代码片段为:
[{"accountId":"abc","items":[{"serviceName":"XYZ","dataCenter":"TG","startTimeUtc":"2017-04-05T19:57:33.509+0000","endTimeUtc":"2017-04-05T19:57:33.509+0000","usage":[{"resourceName":"XYZ_EE_PAAS_GATEWAYS","quantity":7,"units":"number"}]}]},{"accountId":"XYZp1cm9mbe","items":[{"serviceName":"XYZ","dataCenter":"TG","startTimeUtc":"2017-04-05T19:57:33.509+0000","endTimeUtc":"2017-04-05T19:57:33.509+0000","usage":[{"resourceName":"XYZ_EE_PAAS_GATEWAYS","quantity":6,"units":"number"}]}]}]
######################
[{"accountId":"abc","items":[{"serviceName":"XYZ","dataCenter":"TG","startTimeUtc":"2017-04-05T19:59:33.523+0000","endTimeUtc":"2017-04-05T19:59:33.523+0000","usage":[{"resourceName":"XYZ_EE_PAAS_GATEWAYS","quantity":7,"units":"number"}]}]},{"accountId":"XYZp1cm9mbe","items":[{"serviceName":"XYZ","dataCenter":"TG","startTimeUtc":"2017-04-05T19:59:33.523+0000","endTimeUtc":"2017-04-05T19:59:33.523+0000","usage":[{"resourceName":"XYZ_EE_PAAS_GATEWAYS","quantity":6,"units":"number"}]}]}]
######################
[{"accountId":"abc","items":[{"serviceName":"XYZ","dataCenter":"TG","startTimeUtc":"2017-04-05T20:01:33.531+0000","endTimeUtc":"2017-04-05T20:01:33.531+0000","usage":[{"resourceName":"XYZ_EE_PAAS_GATEWAYS","quantity":7,"units":"number"}]}]},{"accountId":"XYZp1cm9mbe","items":[{"serviceName":"XYZ","dataCenter":"TG","startTimeUtc":"2017-04-05T20:01:33.531+0000","endTimeUtc":"2017-04-05T20:01:33.531+0000","usage":[{"resourceName":"XYZ_EE_PAAS_GATEWAYS","quantity":6,"units":"number"}]}]}]
######################此文件每15-16分钟更新一次,其中包含新条目。我想读取文件并将最新的条目(不包括####行)存储在一个json对象中。在java中怎么做?我不想使用15分钟的间隔,因为它不是恒定的。
我的简单要求是,在任何时候,我都会读取该文件,并希望检索###行上的最后一个json。
发布于 2017-06-22 15:19:55
在Java 8中,您可以这样做:
public JsonObject retrieveLastEntry(Path path) throws IOException {
String[] jsonLines = Files.lines(path)
.filter(line -> !line.equals("######################")
.toArray();
String lastJsonLine = jsonLines[jsonLines.length - 1];
return MyFavoriteJsonParser.parse(lastJsonLine);
}MyFavoriteJsonParser指的是您想要使用的任何JSON库(也许可以看看this question)。这里可能没有什么性能方面的考虑。如果您的文件非常大(远远超过几MB),那么.toArray()调用可能不适合您。事实上,如果性能非常重要,您甚至可能需要考虑向后解析文件。但是性能优化的金科玉律是首先使用一个简单的解决方案,看看它是否(以及在哪里)可能不够好。
但是,如果您的JSON是跨行的,则Stream API不是最佳选择。在这种情况下,一个常规的迭代可以解决这个问题:
public JsonObject retrieveLastEntry(File file) throws IOException {
String lastJson = "";
StringBuffer sb = new StringBuffer();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileReader(file), "UTF-8")))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.equals("######################") {
lastJson = sb.toString(); sb.setLength(0);
} else {
sb.append(line).append('\n');
}
}
return MyFavoriteJsonParser.parse(lastJsonLine);
}基本思想是聚合###...之间的行,并在到达新的分隔符时将它们放入一个变量中。您可能仍然希望考虑根本没有条目的情况,并正确处理IOException。
我认为这几乎是一种惯用的方式。
https://stackoverflow.com/questions/44691760
复制相似问题