简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM