gpt4 book ai didi

java - RandomAccessFile 与 FileChannel.open(path);

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:29:25 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com