0

I have a file in which I have to insert array of bytes at specific location of file and then have to read that array from that location. How can I do this in java ?

Mian
  • 63
  • 1
  • 4
  • Begin by writing the necessary code to read an array of bytes from a location. Then come back to us with the question of how to insert an array of bytes. And when you do that, show us your code. – Mike Nakis Dec 04 '16 at 12:09

2 Answers2

0
  1. Load the file as a byte array

  2. Create a byte array having the size of the array you got at 1. + the size of your byte array to insert.

  3. Copy the prefix from the file into your new byte array, that is, the bytes preceding the location you desire

  4. Copy your byte array to be included to the sub-array starting from the location

  5. Copy the suffix of the file into your byte array.

  6. Save your byte array back to the file

This is the writing part. As about the reading part, you will need to load the file into a byte array, described in 1 and then read the subarray from location till length.

Community
  • 1
  • 1
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • @Mian, this is not a code writing service. This answer describes the way the problem should be solved, but assumes that the asker and his classmates actually want to solve it. – Lajos Arpad Dec 04 '16 at 12:36
0

You can use RandomAccessFile (https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html) in order to read or write at arbitrary places in your file.

However, if you need to insert new data without overwriting the old (i.e. shift existing data to the right), that cannot be done directly via the API. You could for example create a new empty file, copy everything from the original file until the specific location, write the new data, append the remaining data from the original file, etc.

Another solution, using FileChannels, and a code example can be found here: https://stackoverflow.com/a/17565931/7247713

Community
  • 1
  • 1
Lucian
  • 181
  • 1
  • 5