在Java中预备行文件 [英] Prepend lines to file in Java

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

问题描述

有没有一种方法可以在Java文件中添加一行,而不需要创建临时文件? / div>

不,在Java中没有办法做到 SAFELY 。在任何主流操作系统中,没有任何文件系统的实现支持这种功能,而且在任何主流编程语言中都不会找到这个功能。

$ b


$ b

真实世界的文件系统是在将数据存储为固定大小的块的设备上实现的。无法实现文件系统模型,您可以将字节插入到文件的中间位置,而不会显着减慢文件I / O,浪费磁盘空间或两者兼而有之。






包含就地重写文件的解决方案本质上是不安全的。如果您的应用程序在插入/重写过程中死亡或电源中断,您可能会丢失数据。我不会推荐在实践中使用这种方法。



使用临时文件。这是更安全的。

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?

解决方案

No, there is no way to do that SAFELY in Java.

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. It is safer.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆