1

I'm trying to implement a log structure file system as an operating system assignment. In it most recent data is placed at end of file. That's why I want to read text file "line-by-line" in reverse order. Is it possible?

Shaban
  • 113
  • 2
  • 11

3 Answers3

3

Check out ReverseLineInputStream:

https://code.google.com/p/lt2-sander-marco/source/browse/src/leertaak2/ReverseLineInputStream.java?spec=svn15&r=15

It refers to the SO question posted at How to read file from end to start (in reverse order) in Java?

in = new BufferedReader (new InputStreamReader (new ReverseLineInputStream(file)));

while(true) {
    String line = in.readLine();
    if (line == null) {
        break;
    }
    System.out.println("X:" + line);
}

(Thanks, @Mark O'Donohue)

Community
  • 1
  • 1
Ron
  • 254
  • 2
  • 17
1

If its line by line - you could pass all the lines into an arraylist and then read it backgrounds using a reverse for loop such as for(int i = list.size()-1;i>=0;i--)

BruceWayne
  • 299
  • 2
  • 8
-1

Yes, but it requires reading through the entire file first. If the file is long, what you can do is split the file into several files, read each file into memory and write the data out to a new file from last line to first line of the old file. When the operation is done, you can delete all the temporary files you created.

La-comadreja
  • 5,627
  • 11
  • 36
  • 64
  • I'd guess because the two solutions are either wrong (you don't need to read the entire file) or weird (why would there be multiple temporary files?) – Dave Newton Feb 17 '14 at 22:47
  • You do need to go through the file to the last line when you scan it. The reason for the multiple files is to reduce the overhead of storing the lines in memory, if the original file is long. – La-comadreja Feb 17 '14 at 22:48
  • No, you can seek to the end with no reads and read backwards, as the reverse file reader above does. That also eliminates any reason to have multiple temporary files. – Dave Newton Feb 17 '14 at 23:00