![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e170. Writing to a Channel with a ByteBufferIt is necessary to use aByteBuffer to write to a channel. This
example retrieves bytes from an input stream and writes them to a
channel using a ByteBuffer. The tricky part of this operation is to
remember to properly set the buffer's position before and after a
write.
try { // Obtain a channel WritableByteChannel channel = new FileOutputStream("outfilename").getChannel(); // Create a direct ByteBuffer; // see also e158 Creating a ByteBuffer ByteBuffer buf = ByteBuffer.allocateDirect(10); byte[] bytes = new byte[1024]; int count = 0; int index = 0; // Continue writing bytes until there are no more while (count >= 0) { if (index == count) { count = inputStream.read(bytes); index = 0; } // Fill ByteBuffer while (index < count && buf.hasRemaining()) { buf.put(bytes[index++]); } // Set the limit to the current position and the position to 0 // making the new bytes visible for write() buf.flip(); // Write the bytes to the channel int numWritten = channel.write(buf); // Check if all bytes were written if (buf.hasRemaining()) { // If not all bytes were written, move the unwritten bytes // to the beginning and set position just after the last // unwritten byte; also set limit to the capacity buf.compact(); } else { // Set the position to 0 and the limit to capacity buf.clear(); } } // Close the file channel.close(); } catch (Exception e) { }
e167. Persisting Changes to a Memory-Mapped ByteBuffer e168. Determining If a ByteBuffer Is Direct e169. Reading from a Channel with a ByteBuffer e171. Writing and Appending a ByteBuffer to a File e172. Copying One File to Another
© 2002 Addison-Wesley. |