What is the best way to write bytes in the middle of a file using Java?
In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.
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();
}
Use RandomAccessFile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With