I don't know where to seek clarifications and confirmations on Java API documentation and Java code, so I'm doing it here.
In the API documentation for FileChannel
, I'm finding off-by-one errors w.r.t. to file position
and file size
in more places than one.
Here's just one example. The API documenation for transferFrom(...)
states:
"If the given position is greater than the file's current size then no bytes are transferred."
I confirmed that the OpenJDK code too contains this code...
public long transferFrom(ReadableByteChannel src, long position, long count)
throws IOException
{
// ...
if (position > size())
return 0;
// ...
}
... in file FileChannelImpl.java
consistent with the documentation.
Now, while the above code snippet and the API documentation appear mutually consistent, I 'feel' that the above should be 'greater than or equal to' and not merely 'greater than' because position
being a 0-based index into the file's data, reading at position == size()
will have no data to return to the caller! (At position == size() - 1
, at least 1 byte -- the last byte of the file -- could be returned to the caller.)
Here are some other similar instances in the same API documentation page:
position(...)
: "Setting the position to a value that is greater than the file's current size is legal but does not change the size of the file." (Should have been 'greater than or equal to'.)transferTo(...)
: " If the given position is greater than the file's current size then no bytes are transferred." (Should have been 'greater than or equal to'.)read(...)
: "If the given position is greater than the file's current size then no bytes are read." (Should have been 'greater than or equal to'.)
Lastly, the documentation section for the return value of read(...)
fails to remain even self-consistent with the rest of the documentation. Here's what it states:
Returns:
The number of bytes read, possibly zero, or -1 if the given position is greater than or equal to the file's current size
So, in this lone instance, I do see them mention the right thing.
Overall, I don't know what to make of all of this. If I write my code today matching this documentation, then a future bug fix in Java (code or documentation) will render my code buggy, requiring a fix from my side as well. If I do the right thing myself today with things as they stand today, then my code becomes buggy to start with!
This could be a bit clearer in the javadoc and is now tracked here:
https://bugs.openjdk.java.net/browse/JDK-8029370
Note that clarifying the javadoc shouldn't change anything for implementations of FileChannel (for example, the transfer methods return the number of bytes transferred so this is 0 when the position is at size or beyond size).