Write bytes into a file without erasing existing bytes [duplicate]
Asked Answered
O

1

9

Possible Duplicate:
Best Way to Write Bytes in the Middle of a File in 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.

What is the best way to do so?

Opener answered 1/10, 2012 at 16:21 Comment(5)
#181908Dupuy
Already tried, unfortunately my implementation does not add bytes but erase existing bytes, what is the trick for actually inserting?Opener
@gtgaxiola: That won't work because it will overwrite the existing bytesFernandina
Then check Jon Skeet's answer #7710856Dupuy
Files don't support inserting bytes. You can only copy existing ones to later in the file.Limbate
H
7

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.

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

  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

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.

Hinch answered 1/10, 2012 at 16:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.