Search code examples
javanio

Why should we use the "write" methods in filechannel while they already exist in RandomAccessFile


This is my code, which uses FileChannel to write to the file:

package logging;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Test {

    public static void main(String args[]){
        try {  

            RandomAccessFile rf = new RandomAccessFile("C:\\Users\\kalyan\\Desktop", "rw");
            FileChannel fc = rf.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.putChar('a');

            while(byteBuffer.hasRemaining()) {
                fc.write(byteBuffer); //usig filechannel to write to the file
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In the above example, I am using FileChannel's write method to write to the file, i.e., fc.write.

Why shouldn't we use rf.write, which already exists in RandomAccessFile?


Solution

  • there's no reason not to use the write() methods which exist on RandomAccessFile. if you happen to be interacting with code which requires a WritableByteChannel, however, you would want to use the FileChannel instead of RandomAccessFile.