0

Here is the file content :

line 1
line 2
line 3
line 4
line 5

Now I want to read the file in reverse order string as below

line 5
line 4
line 3
line 2
line 1

The code I use to read the file line by line is

try (Stream<String> steam = Files.lines(Paths.get("C:\\..\\..\\taxreport.txt")).skip(1)) {
    steam.foreach(i->System.Out.Println(i));
} 
catch (IOException ex) {
    System.out.println(RED_BOLD + "File not Found !!");
}

The code read the file line by line in normal order. But I want to read the line in reverse order.

Can anyone let me know how can I read the line in reverse order.

azro
  • 53,056
  • 7
  • 34
  • 70
San Jaisy
  • 15,327
  • 34
  • 171
  • 290
  • 3
    Possible duplicate of [How to read file from end to start (in reverse order) in Java?](https://stackoverflow.com/questions/8664705/how-to-read-file-from-end-to-start-in-reverse-order-in-java) – soorapadman Sep 01 '17 at 07:17
  • 1
    Possible duplicate of [Java 8 stream reverse order](https://stackoverflow.com/questions/24010109/java-8-stream-reverse-order) – Jotunacorn Sep 01 '17 at 07:20
  • 2
    You need to read the file, store it in a LIFO collection then read that collection. You don't really have a "easy" way to position a cursor in a file. So this will be done in memory. – AxelH Sep 01 '17 at 07:21
  • No reason to down vote this. Above suggestions include non-Java8 and IntStreams. This is text. – Jack Flamp Sep 01 '17 at 07:36

1 Answers1

3

This works for strings:

steam.collect(Collectors.toCollection(LinkedList::new))
    .descendingIterator().forEachRemaining(System.out::println);

This is another example using ArrayList:

    List<String> list = steam.collect(Collectors.toCollection(ArrayList::new));
    Collections.reverse(list);
    list.forEach(System.out::println);
Jack Flamp
  • 1,223
  • 1
  • 16
  • 32