3

I am trying to overwrite last 26 bytes of file. Basically i need to put a few integer and byte variables there. I'm trying to use a DataOutputStream together with FileOutputStream, but these things do not have a seek() method or something like it. So how could i do a writeInt() starting at (file size - 26)? I see there is a write method that accepts an offset but i'm not sure if it is what i want and if so, how to convert int, long and byte variables into byte[] to pass into that method.

Thank you for your advice

1 Answer 1

7

Using RandomAccessFile you can do something along these lines:

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();

I hope it helps! Let me know if it is good enough or not.

Sign up to request clarification or add additional context in comments.

2 Comments

He might use the accessor.writeInt(int) kind of methods directly without packaging everyting into a byte array.
Thank you for the nice example, RandomAccessFile is what i was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.