中将行添加到文件中

中将行添加到文件中

本文介绍了在 Java 中将行添加到文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Java 中为文件添加一行,而无需创建临时文件,并将所需的内容写入其中?

Is there a way to prepend a line to the File in Java, without creating a temporary file, and writing the needed content to it?

推荐答案

不,在 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.

这篇关于在 Java 中将行添加到文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 08:11