Java: How To Use RandomAccessFile and FileChannel to Write to a Specific Location in a File

If there is ever a need to write bytes to a specific location to an existing file, here is an example of how to use the RandomAccessFile and FileChannel Java classes to do so:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Will write bytes to the beginning of an existing file.
 *
 * @author Ryan Chapin
 */
public class RandomAccessFileTest {

    public static void main(String[] args) {

        // Generate input string and the ByteBuffer for it
        String stringToInsert = “This is a string to insert into a file.”;
        byte[] answerByteArray = stringToInsert.getBytes();
        ByteBuffer byteBuffer = ByteBuffer.wrap(answerByteArray);

        File fileToModify = new File(“/path/to/file”);

        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(fileToModify, “rw”);
        } catch (FileNotFoundException e1) {
            // TODO error handling and logging
        }

        FileChannel outputFileChannel = randomAccessFile.getChannel();

        // Move to the beginning of the file and write out the contents
        // of the byteBuffer.
        try {
            outputFileChannel.position(0);

            while(byteBuffer.hasRemaining()) {
                outputFileChannel.write(byteBuffer);
            }
        } catch (IOException e) {
            // TODO error handling and logging
        }

        try {
            outputFileChannel.close();
        } catch (IOException e) {
            // TODO error handling and logging
        }

        try {
            randomAccessFile.close();
        } catch (IOException e) {
            // TODO error handling and logging
        }
    }
}

Leave a Reply