将字节写入文件而不删除现有字节 [英] Write bytes into a file without erasing existing bytes

查看:127
本文介绍了将字节写入文件而不删除现有字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在Java文件中间写入字节的最佳方法

我有一个文件,我需要在其中写入字节。

I have a file in which I need to write bytes.

我知道文件中的哪个位置需要插入特定字节。为了清楚起见,我需要在文件中间写入字节而不删除任何现有字节。然后整个操作应该增加文件的长度。

I know at which position in the file I need to insert specific bytes. To make things clear, I need to write bytes in the middle of the file without erasing any existing bytes. The whole operation should then increase the length of the file.

最好的方法是什么?

推荐答案

执行此操作的唯一方法是移动当前阻碍的字节。根据您必须执行此操作的频率以及文件的大小,创建新文件,复制现有文件以及沿途插入新字节通常更好。

The only way to do this is to movethe bytes that are currently in the way. Depending on how frequently you have to do this, and how large the file is, it's often a better idea to create a new file, copying the existing file and inserting the new bytes along the way.

如果您不经常更新文件,或者它很小(最多可能100 kb),您可以使用 RandomAccessFile

If you need to update the file infrequently, or it's small (up to maybe 100 kb) you can use a RandomAccessFile:


  1. 扩展文件,使用 setLength()方法,将您要插入的字节数添加到 length()返回的内容中方法。

  2. 如果你有足够的内存,创建一个 byte [] ,它将保存从插入点到前一个的所有字节文件结束。

  3. 致电搜寻()以便在插入点定位

  4. 致电 readFully()以填充您的临时数组

  5. 致电 seek() to插入点的位置+要插入的字节数

  6. 调用 write()在此时写入缓冲区

  7. 调用 seek()在插入点重新定位

  8. 调用`write()来写新字节

  1. Extend the file, using the setLength() method, adding the number of bytes you'll be inserting to whatever is returned by the length() method.
  2. If you have enough memory, create a byte[] that will hold all the bytes from the insertion point to the previous end of file.
  3. Call seek() to position at the insertion point
  4. Call readFully() to fill your temporary array
  5. Call seek() to position at the insertion point + the number of bytes to insert
  6. Call write() to write your buffer at that point
  7. Call seek() to reposition at the insertion point
  8. Call `write() to write the new bytes

如果在步骤#2中无法创建足够大的数组,则必须在循环中执行步骤3-6较小的缓冲区。我会使用至少64k缓冲区来提高效率。

If you can't create a large-enough array in step #2, you'll have to perform steps 3-6 in a loop with a smaller buffer. I would use at least a 64k buffer for efficiency.

这篇关于将字节写入文件而不删除现有字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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