排序使用BufferedReader读入

时间:2016-09-29 11:44:40

标签: java bufferedreader

我有一个日志文件,其中2条记录属于同一个ID:

2016-09-29 10:50:48.377 [http-100-exec-1] 4711 ffb0dbcc-2615-40f8 request-log...
2016-09-29 10:50:48.377 [http-100-exec-1] 4711 ffb0dbcc-2615-40f8 response-log...
2016-09-29 10:50:47.749 [http-100-exec-1] 4711 5af0cc2f-5525-4748 request-log...
2016-09-29 10:50:47.867 [http-100-exec-1] 4711 fc2f7ff6-da1e-4309 request-log...
2016-09-29 10:50:47.758 [http-100-exec-1] 4711 5af0cc2f-5525-4748 response-log...
2016-09-29 10:50:47.873 [http-100-exec-1] 4711 fc2f7ff6-da1e-4309 response-log...

现在,我想用BufferedReader打开此文件,并将每行解析为已排序的表。每个解析的行应按表中的ID排序(2个记录始终具有相同的ID)(最后一列,例如ffb0dbcc-2615-40f8)。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

此处的一个选项是使用有序地图存储日志文件中的每一行。

<强>更新

似乎ID可能并非全部不同。在这种情况下,我们可以保留读入记录的计数器,并使用此计数器和实际ID的组合形成哈希键。

例如,ID为ffb0dbcc-2615-40f8的两条记录可能包含密钥ffb0dbcc-2615-40f8-0ffb0dbcc-2615-40f8-1

Map<String, String> map = new TreeMap<>();

BufferedReader br = null;

try {
    String line;

    br = new BufferedReader(new FileReader("C:\\log.txt"));

    int counter = 0;
    while ((line = br.readLine()) != null) {
        String key = line.split("\\s+")[4];
        key = key + "-" + counter;
        map.put(key, line);
        ++counter;
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (br != null) br.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

// now you can iterate over the log statements in order by ID
for (Map.Entry<String,String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " => " + entry.getValue());
}

答案 1 :(得分:1)

使用流

public static List<String> getSortedLines(String path) throws IOException {
    return Files.lines(Paths.get(path))
        .sorted((line1, line2) -> get5thWord(line1).compareTo(get5thWord(line2)))
        .collect(Collectors.toList());
}

public static String get5thWord(String line) {
    return line.split(" ")[4];
}