Who is better in performance filechannel or RandomAccessFile for reading and writing?

7.8k views Asked by At

I recently came across FileChannel, I am a big fan of RandomAccessFile. But I am wondering why would I pick FileChannel over RandomAccessFile for reading from a file and writing that content to another.

Is there any specific performance reason? I dont want to use locking of FileChannel for any purpose as I believe that could be one of the reasons why filechannel can be used. I don't want to use BufferReader or anything like that as suggested in other StackOverflow response.

5

There are 5 answers

1
Evgeniy Dorofeev On

FileChannel API says: A region of a file may be mapped directly into memory; for large files this is often much more efficient than invoking the usual read or write methods.

0
Du-Lacoste On

RandomAccessFile is good in performance plus it allows to read and write most major types directly.

1
Shiva Krish On

FileChannels are safe for use by multiple concurrent threads.

0
user207421 On

There is nothing to choose between them unless you use a FileChannel with direct buffers and never access the data yourself, e.g. you only copy it to a SocketChannel. This is faster because data never has to cross the JNI/JVM boundary.

But I am wondering why you don't pick BufferedReader. It will certainly be orders of magnitude faster than either of these for reading a file line by line.

2
Robert Christian On

RandomAccessFile source:

See that RandomAccessFile is actually using FileChannel under the hood...

public final FileChannel getChannel() {
         synchronized (this) {
             if (channel == null) {
                 channel = FileChannelImpl.open(fd, true, rw, this);

                 /*
                  * FileDescriptor could be shared by FileInputStream or
                  * FileOutputStream.
                  * Ensure that FD is GC'ed only when all the streams/channels
                  * are done using it.
                  * Increment fd's use count. Invoking the channel's close()
                  * method will result in decrementing the use count set for
                  * the channel.
                  */
                 fd.incrementAndGetUseCount();
             }
             return channel;
         }
     }

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/RandomAccessFile.java