-1

I have the below method that tails a file to return last x lines.

private List<String> tailFile(int noOfLines, String source) throws IOException {
    try (Stream<String> stream = Files.lines(Paths.get(FILES_DIRECTORY + "/" + source))) {
        FileBuffer fileBuffer = new FileBuffer(noOfLines);
        stream.forEach(line -> fileBuffer.collect(line));
        return fileBuffer.getLines();
    }
}

I want to insert a new line when I reverse print the contents of the file, but I don't see a new line getting inserted as I reverse but rather my output is all bundled together.

@Override
public ResponseEntity<List<String>> printLastXLines(int limit, String file) throws IOException {
    List<String> response = tailFile(limit, file);
    Collections.reverse(response);
    return new ResponseEntity<>(response, HttpStatus.OK);
}

Current output -

["2021-12-12 21:59:59.590 Returning fetch response for config : secrets, propertiesCount : 1, clientResolution : [SERVER]","2021-12-12 21:59:59.590 Refreshing config : secrets, for change : null","2021-12-12 21:59:59.590 Overriding returned status

Desired output

2021-12-12 21:59:59.590 Returning fetch response for config : secrets, propertiesCount : 1, clientResolution : [SERVER]
2021-12-12 21:59:59.590 Refreshing config : secrets, for change : null
2021-12-12 21:59:59.590 Overriding returned status NO_SUCH_CONFIG for config

I have tried multiple things but I am just not able to do it. How cn I insert a new line while reversing a collection?

halfer
  • 19,824
  • 17
  • 99
  • 186
rickygrimes
  • 2,637
  • 9
  • 46
  • 69
  • Does this answer your question? [Display each list element in a separate line (console)](https://stackoverflow.com/questions/12887857/display-each-list-element-in-a-separate-line-console) – Izruo Dec 13 '21 at 08:33

1 Answers1

0

lines yields all lines without newline character(s). You could do:

Files.lines(...).map(line -> line + "\r\n")

Or do it later, ideally only for the noOfLines.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138