I am creating a file in my application and I am keep on writing some content in to this file.
But after my file reaches to some size, let say 100 lines, I want to erase the first line and write the new line to the bottom.
The requirement is my file should be limited, but it should maintain the latest content that I have written in to file.
Please let me know if its possible in Java? Please let me know if there's any alternative to do this.
Please let me know if its possible in Java?
This can't be done in a simple way. You can only truncate the last part of a file. (This is an inherit limit from the underlying file system, and due to the same reasons as to why you can't insert bytes in the middle of a file.)
You can do it manually by:
n
, of the first line.i = n ... length of file
i
to pos i - n
length of file - n
.Please let me know if there's any alternative to do this.
I suggest you solve it using a cyclic buffer or something similar. Still though, you'd get into trouble if not all lines are equally long, unless you keep the buffer in memory, and dump it to (a cleared) file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With