简体   繁体   English

Java nio FileChannel 写入方法说明

[英]Java nio FileChannel write method clarfication

I have following code to write by file channel我有以下代码要通过文件通道编写

fc.write(bytebuffer, position);

In several tutorials i referred this is ok and it does the job fine.在我提到的几个教程中,这是可以的,它可以很好地完成工作。 But in the javadoc https://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileChannel.html#write-java.nio.ByteBuffer-long- this method returns no of bytes written.但是在 javadoc https://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileChannel.html#write-java.nio.ByteBuffer-long-此方法不返回写入的字节数。 Therefore my question is, is it possible in some case this will write only part of bytebuffer ?因此我的问题是,在某些情况下这是否可能只写入 bytebuffer 的一部分? Do i need to wrap this inside a loop ?我需要将它包装在一个循环中吗? Is this code has bug waiting to happen ?这段代码是否有等待发生的错误?

The method FileChannel.write(...) implements the method WritableByteChannel.write(...) . FileChannel.write(...)方法实现了WritableByteChannel.write(...)方法。 This interface can be used for many kinds of channels.该接口可用于多种渠道。 The WritableByteChannel.write(...) documentation tells: WritableByteChannel.write(...)文档说明:

Unless otherwise specified, a write operation will return only after writing all of the r requested bytes.除非另有说明,写操作只有在写完所有 r 个请求的字节后才会返回。 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.例如,处于非阻塞模式的套接字通道不能写入比套接字输出缓冲区中的空闲字节更多的字节。

But in your case with a FileChannel it will always write and returns the remaining element in your ByteBuffer .但是在您使用FileChannel的情况下,它将始终写入并返回ByteBuffer的剩余元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM