Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

file

java-io

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

like image 285
jjnguy Avatar asked Oct 08 '08 05:10

jjnguy


People also ask

Can we convert byte array to file in 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.


2 Answers

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();
}
like image 154
jjnguy Avatar answered Oct 22 '22 16:10

jjnguy


Use RandomAccessFile

  • Tutorial
  • Javadocs
like image 28
anjanb Avatar answered Oct 22 '22 16:10

anjanb