a.read(b) 方法通常意味着 a 正在从 b 读取某些内容。
我认为这是一个惯例,并且有这样的例子:
InputSream.read() 和 System.in.read() 都是从参数中读取内容。
但是,当涉及到 FileChannel.read() 方法时。这是完全不同的情况:
FileChannel fc = FileChannel.open(Paths.get("test"),StandardOpenOption.READ,StandardOpenOption.WRITE)
ByteBuffer copy = ByteBuffer.allocate(10)
nread = fc.read(copy)
fc.read(copy) 表示将某些内容写入复制缓冲区而不是从复制缓冲区读取。太困惑了,以至于我第一次使用它时,在没有阅读jdk文档的情况下就犯了错误。与fc.write(copy)相同,表示从复制缓冲区读取到文件 channel 。
如果 fc.read(copy) 的命名可以更改为 fc.readTo(copy),Ii 会很有帮助
这是一个令人困惑的设计吗? 为什么API设计者要这样设计?
最佳答案
a.read(b) 表示从a
读取数据并存储到b
中。
read
方法都提供从对象读取的功能。
根据 Java 文档,InputStream :
Reads the next byte of data from the input stream.
同样,FileChannel :
Reads a sequence of bytes from this channel into the given buffer.
约定是统一的,没有歧义。
关于java - Java NIO 中 FileChannel.read()/write() 的命名不明确且令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20393884/