walnutmon walnutmon - 11 months ago 96
Java Question

Add Hexadecimal Header Info to JPEG File Using Java

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

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

Answer Source

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

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) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download