gpt4 book ai didi

Java NIO2 AsynchronousFileChannel 返回 Future ,没有实际值的文档

转载 作者:行者123 更新时间:2023-11-30 06:07:17 26 4
gpt4 key购买 nike

所以我根据网上找到的文档和示例想出了以下函数,以异步方式写入文件:

    public static Future<Integer> createAndWriteToFile(String fullFileName, String content) throws IOException {
Path file = Utils.createFile(fullFileName);
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.WRITE, StandardOpenOption.CREATE);

ByteBuffer buffer = ByteBuffer.wrap(content.getBytes());
Future<Integer> operation = fileChannel.write(buffer, 0);
buffer.clear();

return operation;
}

但是,绝对没有任何文档说明调用 operation.get().intValue() 会发生什么!在 Debug模式下,成功创建/写入文件将返回整数值 23。其他可能的值是什么?文件: https://docs.oracle.com/javase/8/docs/api/java/nio/channels/AsynchronousFileChannel.html#write-java.nio.ByteBuffer-long-

这里: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#get--

Returns: the computed result

有帮助,但没有。

顺便提一个问题 - 让我惊讶的是,Java 被认为是文档记录最完善的语言之一,为什么这个函数没有文档记录?

最佳答案

尽管 docs 中的返回类型没有直接说明。如果您仔细查看那里描述的段落:

This method works in the same manner as the AsynchronousByteChannel.write(ByteBuffer) method, except that bytes are written starting at the given file position. If the given position is greater than the file's size, at the time that the write is attempted, then the file will be grown to accommodate the new bytes; the values of any bytes between the previous end-of-file and the newly-written bytes are unspecified.

所以它说它的行为就像 AsynchronousByteChannel.write(ByteBuffer)这会将您重定向到 Future<Integer> write(ByteBuffer src) 。在那里它指定了 Integer 的内容。 value 的意思,基本上就是写入的字节数。

This method initiates an asynchronous write operation to write a sequence of bytes to this channel from the given buffer. The method behaves in exactly the same manner as the write(ByteBuffer,Object,CompletionHandler) method except that instead of specifying a completion handler, this method returns a Future representing the pending result. The Future's get method returns the number of bytes written.

关于Java NIO2 AsynchronousFileChannel 返回 Future<Integer> ,没有实际值的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51050683/

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