简体   繁体   中英

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

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.

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.

There is nothing to choose between them unless you use a FileChannel with direct buffers and never access the data yourself, eg 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.

RandomAccessFile具有良好的性能,并且允许直接读取和写入大多数主要类型。

FileChannel可以安全地供多个并发线程使用。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM