Odi's astoundingly incomplete notes
New entries | CodeJDK nio Bug
It's once a year or so that I find a bug in the Java library. This time it's in the
By the way, most sample code on the net for copying data with nio is wrong. The following is the correct way of doing it. The crux is that the read and write method may not read/write all of the buffer!
java.nio.Channels.newChannel
method. It contains a buggy check for a class name:
String inClass = in.getClass().toString();
if (inClass.equals("java.io.FileInputStream"))
This test will never succeed because toString does not return the class name. They should have used getClass().getName()
instead. It's not a very bad bug, but it prevents some optimizations with FileChannels.By the way, most sample code on the net for copying data with nio is wrong. The following is the correct way of doing it. The crux is that the read and write method may not read/write all of the buffer!
java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(bufsize); buffer.clear(); // the loop is safe for partial reads and writes while (in.read(buffer) >= 0 || buffer.position() > 0) { buffer.flip(); out.write(buffer); buffer.compact(); }Similar with transferTo/From:
FileChannel fc = ... long len = fc.size(); long pos = 0L; while (pos < len) { pos += fc.transferTo(pos, len, outch); }
FileChannel fc = ... long len = fc.size(); long pos = 0L; while (pos < len) { pos += fc.transferFrom(inch, pos, len); }
Alegedly fixed in 1.6
Add comment