So I came up with the following function based on the docs and examples I found online, to write files in async way:
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;
}
However, there is absolutely no documentation on what to expect from calling operation.get().intValue()
!
In debug mode, successful file creation/writing returns Integer value 23.
What are other possible values?
Docs:
https://docs.oracle.com/javase/8/docs/api/java/nio/channels/AsynchronousFileChannel.html#write-java.nio.ByteBuffer-long-
And here: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#get--
Returns: the computed result
Helpful, its not.
As an aside question - it surprised me, Java is considered one of the most well documented languages, how comes this function is not documented?
Even though not directly stated on the return type in the docs. If you look closely at the paragraph described there:
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.
So it says it behaves just like AsynchronousByteChannel.write(ByteBuffer)
which redirects you to Future<Integer> write(ByteBuffer src)
. There it specifies what the Integer
value means, which is basically the number of bytes written.
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.