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?
Asked
Active
Viewed 3,709 times
1
-
3Wait, why is that a reason to read from the end? – Dave Newton Feb 17 '14 at 22:20
-
You might have to do it yourself: Seek to the end of the file, then scan backwards for newline characters. – jia103 Feb 17 '14 at 22:21
-
@DaveNewton: Because, In log based file system(with write-once policy) new and modified data is stored at the end of already written data. In my case at end of file. – Shaban Feb 17 '14 at 22:50
-
So why do you need to read it in reverse order? You're talking about writing. – Dave Newton Feb 17 '14 at 23:01
3 Answers
3
Check out ReverseLineInputStream:
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)
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
-
ok but still might place a heavy burden on memory if the file is long. – La-comadreja Feb 17 '14 at 22:31
-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