有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java nio文件通道写入方法说明

我有以下代码要通过文件通道编写

fc.write(bytebuffer, position);

在一些教程中,我提到这是好的,它做的很好。但是在javadochttps://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileChannel.html#write-java.nio.ByteBuffer-long-中,此方法不返回写入的字节数。因此我的问题是,在某些情况下,这是否可能只写bytebuffer的一部分?我需要把这个包在一个圈里吗?这段代码是否有bug等待发生


共 (1) 个答案

  1. # 1 楼答案

    方法FileChannel.write(...)实现了方法WritableByteChannel.write(...)。该接口可用于多种通道。{}文档说明:

    Unless otherwise specified, a write operation will return only after writing all of the r requested bytes. Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all. A socket channel in non-blocking mode, for example, cannot write any more bytes than are free in the socket's output buffer.

    但是在使用FileChannel的情况下,它将始终写入并返回ByteBuffer中的剩余元素