java - RandomAccessFile 与 FileChannel.open(path);

标签 java io nio

FileChannel.open(path) 方法返回什么样的FileChannel 对象?

像下面这样还允许随机访问吗?

RandomAccessFile ra = new RandomAccessFile("RandomIndeed","rw");
    FileChannel fc1 = ra.getChannel();

fc1和下面的实例fc有什么区别:

FileChannel fc = FileChannel.open(path);

基本上我想知道上面创建的两个对象之间的区别是什么,因此 fc1fc

提前致谢。

最佳答案

RandomAccessFile 实例得到的 FileChannel 实例携带了它所创建的对象的随机访问行为,在这种情况下 fc1 是同步的ra 对象。可以看到在javadoc中有描述

Changing the channel's position, whether explicitly or by reading or writing bytes, will change the file position of the originating object, and vice versa. Changing the file's length via the file channel will change the length seen via the originating object, and vice versa. Changing the file's content by writing bytes will change the content seen by the originating object, and vice versa.

但是使用 FileChannel.open() 创建的 FileChannel 实例是 fc 没有这种行为。这对于您从 Streams 获得的 FileChannel 实例来说是正确的。它只保证文件的 View 在同一程序创建的对象之间是一致的。希望这对您有所帮助。

关于java - RandomAccessFile 与 FileChannel.open(path);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16465088/

相关文章:

java - 如何从网站下载文件?

Java 线程被通知调用卡住了

java - 在方法参数中指定文件类型

python - 有人可以在 python (scipy.io) 中解释 mdict,例如在 scipy.io.savemat() 中吗?

java - ProcessBuilder 处理输出

mongodb - 在 MongoDB 中,最大化每日日志文档写入性能的策略

java - Java 中的 "regular file"是什么?

java - MappedByteBuffer 滑动窗口

java - 如何返回一维数组?

java - 如何检测 BlackBerry 设备的屏幕方向是 "natural"?