0

I am a beginner in java and I am having trouble attempting this. I have a text file which prints line by line. The ReadBuffer helps my class to read the text file and print it onto a gui. However, it is currently reading from the top(which is the oldest print) to bottom(which is the latest print). How do I print from bottom to top without using any external libraries?

kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • Will your program always read all lines, or is the intension to print only the last N lines of the file? Why do you tag this BufferedWriter when only reading is an issue? – Thomas Weller Dec 02 '19 at 16:51
  • Read all lines into a `List`. Now go through the list in reverse or reorder the list. https://stackoverflow.com/questions/3962766/how-to-get-a-reversed-list-view-on-a-list-in-java – SedJ601 Dec 02 '19 at 16:58
  • @Sedrick: you definitely don't want to do this on a 10 GB file. – Thomas Weller Dec 02 '19 at 17:02
  • @ThomasWeller that's true, but where did you read that he was using a file that big? Seeing beginner, I assumed this is a class assignment. The file is most likely small. – SedJ601 Dec 02 '19 at 17:04
  • @Sedrick: if it's an assignment, then it's even more important to actually read the file backwards, isn't it? Otherwise you haven't learned anything. – Thomas Weller Dec 02 '19 at 17:06
  • @ThomasWeller your link is the better solution. I have assumed too much:) – SedJ601 Dec 02 '19 at 17:08

2 Answers2

0

To add to Juans, there is actually a lines() method in BufferedReader which will return a stream. From there you can iterate in reverse.

-1

If I recall correctly, BufferedReader has a readLine() method. You could read all the lines of the file, store them in an ArrayList<> and read the ArrayList from end to start.

Juan Dario
  • 46
  • 7
  • a) this still reads the file from top to bottom and thus doesn't answer the question b) you don't want to do this on large files. – Thomas Weller Dec 02 '19 at 17:03