Prepend lines to file in Java

No, there is no way to do that SAFELY in Java. (Or AFAIK, any other programming language.)

No filesystem implementation in any mainstream operating system supports this kind of thing, and you won’t find this feature supported in any mainstream programming languages.

Real world file systems are implemented on devices that store data as fixed sized “blocks”. It is not possible to implement a file system model where you can insert bytes into the middle of a file without significantly slowing down file I/O, wasting disk space or both.


The solutions that involve an in-place rewrite of the file are inherently unsafe. If your application is killed or the power dies in the middle of the prepend / rewrite process, you are likely to lose data. I would NOT recommend using that approach in practice.

Use a temporary file and renaming. It is safer.

Leave a Comment