Who does better in filechannel or RandomAccessFile for reading and writing?
I recently met FileChannel , I'm a big fan of RandomAccessFile . But I'm wondering why I would choose FileChannel
over RandomAccessFile
to read from a file and write that content to another.
Is there a specific reason? I don't want to use blocking FileChannel
for any purpose, as I believe this might be one of the reasons why a file pipe can be used. I don't want to use BufferReader
or anything like that as suggested in another StackOverflow answer.
source to share
You can't choose between the two unless you use FileChannel
with direct buffers and never access the data yourself, for example. you only copy it to SocketChannel.
This is faster because the data should never cross the JNI / JVM boundary.
But I'm wondering why you don't choose BufferedReader
. It will certainly be an order of magnitude faster than any of them for reading the file line by line.
source to share
RandomAccessFile source:
See what RandomAccessFile actually uses 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 use count. Invoking the channel close()
* method will result in decrementing the use count set for
* the channel.
*/
fd.incrementAndGetUseCount();
}
return channel;
}
}
source to share