简体   繁体   English

使用RandomAccessFile删除文件内容

[英]Delete file contents using RandomAccessFile

I have a file which contains lot of zeros and as per the requirement the zeros in the file are invalid. 我有一个包含很多零的文件,根据要求,文件中的零是无效的。 I am using RandomAccessFile api to locate data in the file. 我正在使用RandomAccessFile api在文件中定位数据。 Is there way so that all the zeros can be removed from the file using the same api. 有没有办法使所有零都可以使用相同的api从文件中删除。

You'll have to stream through the file and write out the content, minus the zeros, to a separate temporary file. 您将必须流传输该文件并将内容(减去零)写到一个单独的临时文件中。 You can then close and delete the original and rename the new file to the old file name. 然后,您可以关闭并删除原始文件,然后将新文件重命名为旧文件名。 That's your best alternative for this particular use case. 对于这种特定的用例,这是您的最佳选择。

You can use RandomAccessFile to read the files' data, and when you reach a point where you need to change the data you can overwrite the existing number of bytes with equal number of bytes. 您可以使用RandomAccessFile来读取文件的数据,当到达需要更改数据的位置时,可以用相等的字节数覆盖现有的字节数。 It's iff the new value is exactly the same length as the old value. 如果新值与旧值的长度完全相同。

With RandomAccessFile its difficult and equally complex when the size of two, the one being changed and the new value are different. 使用RandomAccessFile时,当两个大小(一个被更改的值和新值)不同时,将变得困难而同样复杂。 It involves a lot of seeks, reads and writes to move data back 它涉及大量查找,读取和写入操作,以将数据移回

Try to read the whole file, change the bits you have to change and write a new file. 尝试读取整个文件,更改要更改的位并写入新文件。 You might process one line at a time or read the whole file into memory, modify it and write it all back out again. 您可以一次处理一行,也可以将整个文件读入内存,对其进行修改,然后再次全部写回。 It is a good idea to perform the edit in the following manner: 最好按以下方式执行编辑:

  1. Read file 读取档案
  2. Write to Temporary File [just to back-up] 写入临时文件[仅备份]
  3. Rename original to back-up 将原件重命名为备份
  4. Work on Temporary file. 处理临时文件。
  5. Remove Backup if you were successful. 如果成功,请删除备份。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM