views:

1185

answers:

3

What is the best way to write bytes in the middle of a file using Java?

+5  A: 

Use RandomAccessFile

anjanb
A: 

Open the file in write mode without truncating it, seek to the desired offset, and write the desired data. Just be careful about text/binary mode.

Adam Rosenfield
+5  A: 

Reading and Writing in the middle of a file is as simple as using a RandomAccessFile in Java.

RandomAccessFile, despite its name, is more like an InputStream and OutputStream and less like a File. It allows you to read or seek through bytes in a file and then begin writing over whichever bytes you care to stop at.

Once you discover this class, it is very easy to use if you have a basic understanding of regular file i/o.

A small example:

public static void aMethod(){
    RandomAccessFile f = new RandomAccessFile(new File("whereDidIPutTHatFile"), "rw");
    long aPositionWhereIWantToGo = 99;
    f.seek(aPositionWhereIWantToGo); // this basically reads n bytes in the file
    f.write("Im in teh fil, writn bites".getBytes());
    f.close();
}
jjnguy