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

标签 java nio2

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

    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/

相关文章:

java - 为什么 Java 7 中没有 Files.readAllLines(String path)?

java-7 - 如何将具有属性/权限的目录从一个位置复制到另一个位置?

java - 在Spring MVC中将复选框值插入数据库

java - 使用 Spring JdbcTemplate 时如何动态更改数据库/目录

java - Hibernate:将现有子实体添加到具有 OneToMany 双向关系的新实体并将其保留 ('detached entity passed to persist' )

java - 如何在 Java 7 中用 nio 替换 File.listFiles(FileFilter filter)?

java - 我应该关闭使用 java.nio.file.Files.newInputStream 创建的 Streams 吗?

java - Hibernate 局部变量的自定义注释

Java:如何将 com.google.api.services.drive.model.File 转换为 InputStream?

java - AsynchronousFileChannel 是否有等同于 transferTo 的东西?