且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Java 中将行添加到文件中

更新时间:2023-12-02 23:36:16

不,在 Java 中没有办法安全做到这一点.(或 AFAIK,任何其他编程语言.)

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.

现实世界的文件系统是在将数据存储为固定大小的块"的设备上实现的.不可能实现这样一种文件系统模型,即您可以在不显着减慢文件 I/O、浪费磁盘空间或两者兼而有之的情况下将字节插入文件中间.

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.

涉及文件就地重写的解决方案本质上是不安全的.如果您的应用程序在 prepend/rewrite 过程中被终止或电源中断,您很可能会丢失数据.我不建议在实践中使用这种方法.

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.