views:

265

answers:

2

I need to add header info to a JPEG file in order to get it to work properly when shared on some websites, I've tracked down the correct info through a lot of Hex digging, but now I'm kind of stuck trying to get it into the file. I know where in the file it needs to go, and I know how long it is, my problem is that RandomAccessFile just overwrites existing data in the file and FileOutputStream appends the data to the end. I don't want either, I want to INSERT data starting at the third byte.

My example code:

File fileToChange = new File("someimage.jpg");

byte[] i = new byte[2];
i[0] = (byte)Integer.decode("0xcc");
i[1] = (byte)Integer.decode("0xcc");

RandomAccessFile f = 
    new RandomAccessFile(new File("videothing.jpg"), "rw");
long aPositionWhereIWantToGo = 2;
f.seek(aPositionWhereIWantToGo); // this basically reads n bytes in the file
f.write((byte[])i);
f.close();

So this doesn't work because it overwrites, and does not insert, I can't find any way to just insert data into a file

+2  A: 

Rewrite a copy of the file inserting the data into it at the desired place. Or write an OutputStream that injects the data if you want to do it on-the-fly while transmitting, for example, an HTTP response.

Software Monkey
A: 

You will need to use OutputSteam and InputStream in tandem. Read the file using InputStream and write first 2 bytes from the orignal file. The insert your hexadecimal content and then read rest of the input stream and write to the outputstream.

Method to be used for reading

public int read(byte b[], int off, int len)

Method to be used for writing

public void write(byte b[], int off, int len)

Fazal