Best Way to Write Bytes in the Middle of a File in Java
Asked Answered
M

4

18

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

Machellemachete answered 8/10, 2008 at 5:0 Comment(0)
M
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();
}
Machellemachete answered 8/10, 2008 at 21:54 Comment(4)
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?Corned
If you do not know the position, then you need to open the file and read it to find where you need to write.Machellemachete
my "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 filesCorned
Note that the RandomAccessFile would overwrite the current content of the file from aPositionWhereIWantToGoBrandes
I
6

Use RandomAccessFile

Impolitic answered 8/10, 2008 at 5:3 Comment(1)
The tutorial linked to doesn't actually mention the RandomAccessFile class. Maybe this one instead: tutorials.jenkov.com/java-io/randomaccessfile.htmlPew
F
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.

Fief answered 8/10, 2008 at 5:3 Comment(0)
L
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.

Lute answered 12/11, 2019 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.