Drextor Drextor - 2 months ago 8
Java Question

Sorted Read in with BufferedReader

I have a Log File where 2 records belong together with the same 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...


Now, I want to open this file with a
BufferedReader
and parse each line into a sorted table. Each parsed line should be sorted by the ID (2 records have always the same ID) (last column, e.g.
ffb0dbcc-2615-40f8
), in the table.

How can I do this?

Answer

One option here would be to use a sorted map to store each line from the log file.

Update:

It appears that the IDs may not all be distinct. In this case, we can keep a counter of the records read in, and form the hash key using a combination of this counter and the actual ID.

For example, the two records with ID ffb0dbcc-2615-40f8 might have keys ffb0dbcc-2615-40f8-0 and ffb0dbcc-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());
}
Comments