Question

a.read(b) method in generally imply that a is reading something from b.

I think it's a convention and there're examples like that:

InputSream.read() and System.in.read() are all about reading something from the parameter.

However, when it comes to FileChannel.read() method. It's a totally difference situation:

FileChannel fc = FileChannel.open(Paths.get("test"),StandardOpenOption.READ,StandardOpenOption.WRITE)
ByteBuffer copy = ByteBuffer.allocate(10)
nread = fc.read(copy)

fc.read(copy) means that writing something to copy buffer instead of reading from copy buffer. It's so confusing that I make mistakes using it at first time without reading the jdk documents. The same as fc.write(copy), which means that reading from the copy buffer to file channel.

Ii's helpful if the naming of fc.read(copy) could be changed as fc.readTo(copy)

Is it a confusing design? why the API designer should design like that?

Was it helpful?

Solution

a.read(b) means data is read from a and stored into b.

read method of any class provides the functionality to read from the object.

As per Java Documentation, InputStream :

Reads the next byte of data from the input stream.

Similarly, FileChannel :

Reads a sequence of bytes from this channel into the given buffer.

The convention is uniform and there is no ambiguity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top