What is the best way to write bytes in the middle of a file using Java?
Asked
Active
Viewed 1.6k times
4 Answers
25
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
- 136,852
- 53
- 295
- 323
-
what if i do not know the position or if i have hundreds of files where i have to insert data in the middle of them after some specified text? – VENKI Jan 20 '12 at 15:39
-
If you do not know the position, then you need to open the file and read it to find where you need to write. – jjnguy Jan 20 '12 at 17:27
-
1my "file.txt" contains text like this "hi how you (newline) I am fine thanks" now i want to insert "are" in the middle of the text what i have to do? while doing this please mind that we are working with high amount of sized files – VENKI Jan 21 '12 at 07:35
-
1Note that the RandomAccessFile would overwrite the current content of the file from aPositionWhereIWantToGo – super1ha1 Mar 29 '16 at 15:47
0
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
- 390,455
- 97
- 512
- 589
0
I think it’s best to create file chunks every time. And when the file is downloaded, connect them together. Now I'm working on it.

Master
- 690
- 6
- 18