Java - overwrite part of a binary file

I am trying to overwrite the last 26 bytes of a file. Basically I need to put a few integer and byte variables. I'm trying to use a DataOutputStream along with a FileOutputStream, but these things don't have a seek () method or anything like that. So, how can I do writeInt () starting with (file size - 26)? I see that there is a recording method that accepts the offset, but I'm not sure if this is what I want, and if so, how do I convert the int, long and byte variables to bytes [] to go to this method.

thanks for your advice

+3
source share
2 answers

Use RandomAccessFile- it has all the methods you may need.

http://download.oracle.com/javase/1.5.0/docs/api/java/io/RandomAccessFile.html

+5

RandomAccessFile, - :

File myFile = new File (filename);
//Create the accessor with read-write access.
RandomAccessFile accessor = new RandomAccessFile (myFile, "rws");
int lastNumBytes = 26;
long startingPosition = accessor.length() - lastNumBytes;

accessor.seek(startingPosition);
accessor.writeInt(x);
accessor.writeShort(y);
accessor.writeByte(z);
accessor.close();

, ! , .

+4

All Articles