写入时移动文件?
使用 FileWriter 写入文件时是否可以移动文件的内容?
我需要将数据常量写入文件的头部,如果这样做,它会覆盖该文件。
我应该使用什么技术来执行此操作,或者我应该在每次文件写入时制作文件副本(新数据位于顶部)?
Is it possible to shift the contents of a file while writing to it using FileWriter?
I need to write data constants to the head of the file and if I do that it overwrites the file.
What technique should I use to do this or should I make make copies of the file (with the new data on top) on every file write?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想覆盖文件的某些字节而不是其他字节,可以使用查找和写入来执行此操作。如果您想更改文件中每个字节的内容(例如,通过在文件开头添加一个字节),那么您需要编写一个新文件,并可能在编写完成后重命名它。
想一想这个问题的答案:“完成后,偏移量 x 处的字节内容是什么?”。如果对于 x 的大部分可能值,答案是“与以前不同”,那么您需要一个新文件。
If you want to overwrite certain bytes of the file and not others, you can use seek and write to do so. If you want to change the content of every byte in the file (by, for example, adding a single byte to the beginning of the file) then you need to write a new file and potentially rename it after you've done writing it.
Think of the answer to the question "what will be the contents of the byte at offset x after I'm done?". If, for a large percent of the possible values of x the answer is "not what it used to be" then you need a new file.
与其与“完成后偏移 x 处的字节的内容是什么?”这个问题争论,不如改变思维方式,问问为什么文件系统或硬盘固件不能这样做:a)提供另一种访问文件的模式[比方说,内联] b) 将文件的长度增加在前面、中间甚至末尾添加的字节数 c) 将从横截面开始的每个字节移动newcontent.length 位置
在磁盘固件或文件系统实现级别处理这些操作会更容易、更快捷,而不是将这项工作留给应用程序开发人员。我希望文件系统编写者或硬盘供应商能够尽快提供这样的功能。
问候,
桑巴舞
Rather than contending ourselves with the question "what will be the contents of the byte at offset x after I'm done?", lets change the mindset and ask why can't the file system or perhaps the hard disk firmware do : a) provide another mode of accessing the file [let's say, inline] b) increase the length of the file by the number of bytes added at the front or in the middle or even at the end c) move each byte that starts from the crossection by the newcontent.length positions
It would be easier and faster to handle these operations at the disk firmware or file system implementation level rather than leaving that job to the application developer. I hope file system writers or hard disk vendors would offer such feature soon.
Regards,
Samba