Android Question Read only last line in a file

pazzokli

Active Member
Licensed User
Longtime User
Hi forum,
I' ve a big text file with a lot of line. I want read only last line or last x lines without read all the lines.
This file store date and room temperature every 10 minutes and add a line each time. I want display a graph of some hours only, but problem is that I don't know how many lines there are in this file and I implemented a cicle to read all the line and use last 144 (for show 24h) only.
This take a lot of time.
There is a fastest way?

Thanks
 

MarkusR

Well-Known Member
Licensed User
Longtime User
i wonder why there is no seek to a position
command.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
B4X:
    Dim raf As RandomAccessFile
    raf.Initialize(File.DirApp,"1.json", True)
    raf.CurrentPosition = 150
    Dim bytesread(50) As Byte
    raf.ReadBytes(bytesread,0,50,raf.CurrentPosition)
    Log(BytesToString(bytesread,0,bytesread.Length,"UTF-8"))
 
Upvote 0

udg

Expert
Licensed User
Longtime User
I wonder why there is no seek to a position command.
My whole point, in a way, was about that.
The conclusion is that an InputStream (since it is a stream) is kind of an object where data flow from start to end so you can't "rewind". Just for completeness, you could skip from its current position forward AND eventually set a mark point and reset back to it.
BUT, when you set the mark point, it seems that you have to "contract" a max number of bytes "to remember", past which the contract is no more valid; that means you could rewind to mark as long as you didn't move forward past the limit you set in the contract.

As an extreme case, you could set the mark point to position zero and have the contract equal to the size of your file. In that case you could rewind to the beginning, then skip forward wherever you need. This in theory. If you account for the size of some large file it would be like reading all of it in memory and there's no reason to work this way.

So, to move forth and back on a file you should use RAF (like Manfred showed above).
 
Upvote 0

MarkusR

Well-Known Member
Licensed User
Longtime User
i overlooked the RandomAccessFile class, i only looked at file, inputstream and textreader classes.
helpful would be in the "help" links to related content. something like an overview grouped by file access.
 
Upvote 0
Top