I'm writing a library for reading/writing bits from/to Streams/Channels.
When working with Channels I use 1-byte-long ByteBuffer.
Here comes how to read/write with those ByteBuffer.
//@Override // commented for pre 5
public int readUnsignedByte() throws IOException {
buffer.clear(); // ------------------------------------------- clear
for (int read = -1;;) {
read = input.read(buffer); // ----------------------------- read
if (read == -1) {
throw new EOFException("eof");
}
if (read == 1) {
break;
}
}
buffer.flip(); // --------------------------------------------- flip
return (buffer.get() & 0xFF); // ------------------------------- get
}
//@Override // commented for pre 5
public void writeUnsignedByte(final int value) throws IOException {
buffer.put((byte) value); // ----------------------------------- put
buffer.flip(); // --------------------------------------------- flip
while (output.write(buffer) != 1); // ------------------------ write
buffer.clear(); // ------------------------------------------- clear
}
In this case, does allocateDirect(1)
is always better than allocate(1)
?