Updating a specific portion of a text file in java

前端 未结 2 1617
被撕碎了的回忆
被撕碎了的回忆 2021-01-23 21:46

In my program I need to update the Balance column of the text file each time the user does a withdrawal. I used both the write methods as well as the append methods, but to no a

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-23 22:30

    The only simple way to do this is to rewrite the entire contents of the text file every time you make any change. But this is awful for several reasons:

    • It is very slow.
    • It can only be done by one thread at a time, so it's not easily scalable.
    • If your application crashes during the write you could lose all your data.

    You can use fixed width columns to allow seeking and writing into your file without having to rewrite the entire file, but there are still problems:

    • If you ever need to store a value that exceeds the width needed by your column then you have a problem.
    • You still need to read the entire file (worst case - half on average) to find the record you want to modify (keeping a cache in memory will help here).

    I'd suggest that you use a database instead. There are databases that you can install locally and require no administation (SQLite for example).

提交回复
热议问题