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.

+3


source to share


5 answers


The FileChannel API says: The file area can be mapped directly to memory; for large files, this is much more efficient than using conventional read or write methods.



0


source


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.

0


source


RandomAccessFile is good for performance and also allows you to read and write most of the basic types directly.

-1


source


FileChannel is safe for use by multiple concurrent threads.

-1


source


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;
         }
     }

      

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

-2


source







All Articles