使用 BufferedReader 排序读入

Sorted Read in with 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 打开这个文件并将每一行解析为排序的 table。每个解析的行都应按 ID 排序(2 条记录始终具有相同的 ID)(最后一列,例如 ffb0dbcc-2615-40f8),在 table.

我该怎么做?

这里的一个选项是使用排序映射来存储日志文件中的每一行。

更新:

看来 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());
}

使用流

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