Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the file size in Java

Tags:

java

android

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.

like image 946
brig Avatar asked Dec 21 '22 10:12

brig


1 Answers

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:

  1. Figuring out the byte-length, n, of the first line.
  2. For i = n ... length of file
    1. Write byte at pos i to pos i - n
  3. Truncate the file to length 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.

like image 129
aioobe Avatar answered Jan 02 '23 23:01

aioobe