Hamza Amamy Hamza Amamy - 4 years ago 139
Java Question

FILO java writing strategy in a text file

I want to apply the "First In last out" strategy in a text file

Assuming that I have a file containing some "measurements", and I don't want it to contain more than 10 lines, I'm accessing to it to :

  • If < 10 = insert a value and write lines in other support

  • If >= 10 = insert a value and write only the last 10 lines (and delete others)

To make it simple, assuming that my file look like
(to not charge it some much, I'll just put some line break as it was in java)

File :

1 "\n" 2 "\n" 3 "\n" 4 "\n" 5 "\n" 6 "\n" 7 "\n" 8 "\n" 9 "\n" 10

Now I want to insert a new data in the file and get the last 10, new data is 11 :

My file should look like :

2 "\n" 3 "\n" 4 "\n" 5 "\n" 6 "\n" 7 "\n" 8 "\n" 9 "\n" 10 "\n" 11

Is there a way to do this in java ?

Answer Source

Sure is.

  • Write a method that reads that file into a helpful data structure, for example a List<Integer>
  • Then manipulate the content of that data structure, for example using List.remove(int index) to remove the first entry; and then append that one new entry
  • Then write that data structure back into your file
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download