The Story
I've been having a problem lately...
I have to read a file in reverse character by character without running out of memory.
I can't read it line-by-line and reverse it with StringBuilder because it's a one-line file that takes up to a gig (GB) of I/O space.
Hence it would take up too much of the JVM's (and the System's) Memory.
I've decided to just read it character by character from end-to-start (back-to-front) so that I could process as much as I can without consuming too much memory.
What I've Tried
I know how to read a file in one go:
(MappedByteBuffer+FileChannel+Charset which gave me OutOfMemoryExceptions)
and read a file character-by-character with UTF-8 character support
(FileInputStream+InputStreamReader).
The problem is that FileInputStream's #read() only calls #read0() which is a native method!
Because of that I have no idea about the underlying code...
Which is why I'm here today (or at least until this is done)!
This will do it (but as written it is not very efficient).
This could be improved by increasing the buffer size and making equivalent adjustments in the mark and skip arguments.
Updated Version
I wasn't fully satisfied with my answer so I made it more general. Some variables could have served double duty but using meaningful names helps clarify how they are used.
Markmust be used soresetcan be used. However, it only needs to be set once and is set to position 0 outside of the main loop. I do not know if marking closer to the read point is more efficient or not.skipCnt- initally set tofileLengthit is the number of bytes to skip before reading. If the number of bytes remaining is greater than the buffer size, then the skip count will beskipCnt - bsize. Else it will be0.remainingBytes- a running total of how many bytes are still to be read. It is updated by subtracting the currentreadCnt.readCnt- how many bytes to read. IfremainingBytesis greater thanbsizethen set tobsize, else set toremainingBytesThe while loop continuously reads the file starting near the end and then prints the just read information in reverse order. All variables are updated and the process repeats until the
remainingBytesreaches 0.