4

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.

4

5 回答 5

0

FileChannel API 说:文件的一个区域可以直接映射到内存中;对于大文件,这通常比调用通常的读取或写入方法更有效。

于 2014-11-27T05:16:39.210 回答
0

除非您使用带有直接缓冲区的 a 并且从不自己访问数据,否则它们之间没有任何选择FileChannel,例如您只将其复制到 aSocketChannel.这更快,因为数据永远不必跨越 JNI/JVM 边界。

但我想知道你为什么不选择BufferedReader. 对于逐行读取文件,它肯定会比其中任何一个都快几个数量级。

于 2014-12-05T00:52:48.523 回答
-1

RandomAccess 文件来源:

看到 RandomAccessFile 实际上是在后台使用 FileChannel ......

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

于 2015-02-06T20:31:43.327 回答
-1

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

于 2014-11-27T06:11:52.520 回答
-1

RandomAccessFile 性能好,而且它允许直接读取和写入大多数主要类型。

于 2014-11-27T05:30:37.273 回答