R
Roedy Green
I have been looking an nio trying to figure out how it works, and
hence where it would pay to flip over to it.
It uses an underlying InputStream. So if you read the whole
InputFileStream into a byte array in one i/o, NIO would do you no
good. It uses the same methods you do to get raw bytes.
However, if you used nio to read an encoded character file, you have
to do the decoding yourself, but the slick thing is, the output can go
to a CharBuffer. This saves quite a bit of overhead. decode does not
need to know in advance precisely how may chars the stream will decode
to. That saves a copy for trimming to size. And since it effectively
ends up with a char[] instead of a string, than saves yet another
copy. Bravo! The catch is CharBuffer is not quite as convenient as
String for processing.
I love the code to copy from one stream to another with a chunk buffer
in the middle. So simple compared with doing it yourself as I do in
FileTransfer. see http://mindprod.com/products1.html#FILETRANSFER.
The buffers magically handle the housekeeping to deal with short
reads, and the partial block at the end.
The inner loop for a copy is just:
inchannel.read( buffer );
outchannel.write( buffer );
There is no copying. You can even arrange that physical i/o happens
from the buffer array.
The basic idea is, ordinary i/o appears as a stream of individual
bytes or chars. NIO, i/o occurs in buffer fulls, and you are acutely
away of the buffer and can peek and poke it yourself. It is a little
bit like PL/1 based i/o.
hence where it would pay to flip over to it.
It uses an underlying InputStream. So if you read the whole
InputFileStream into a byte array in one i/o, NIO would do you no
good. It uses the same methods you do to get raw bytes.
However, if you used nio to read an encoded character file, you have
to do the decoding yourself, but the slick thing is, the output can go
to a CharBuffer. This saves quite a bit of overhead. decode does not
need to know in advance precisely how may chars the stream will decode
to. That saves a copy for trimming to size. And since it effectively
ends up with a char[] instead of a string, than saves yet another
copy. Bravo! The catch is CharBuffer is not quite as convenient as
String for processing.
I love the code to copy from one stream to another with a chunk buffer
in the middle. So simple compared with doing it yourself as I do in
FileTransfer. see http://mindprod.com/products1.html#FILETRANSFER.
The buffers magically handle the housekeeping to deal with short
reads, and the partial block at the end.
The inner loop for a copy is just:
inchannel.read( buffer );
outchannel.write( buffer );
There is no copying. You can even arrange that physical i/o happens
from the buffer array.
The basic idea is, ordinary i/o appears as a stream of individual
bytes or chars. NIO, i/o occurs in buffer fulls, and you are acutely
away of the buffer and can peek and poke it yourself. It is a little
bit like PL/1 based i/o.