- All Superinterfaces:
- Channel, Closeable
- All Known Subinterfaces:
- ByteChannel, GatheringByteChannel
- All Known Implementing Classes:
- DatagramChannel, FileChannel, Pipe.SinkChannel, SocketChannel
- See Also:
- Top Examples, Source Code
int write(ByteBuffer src)
throws IOException
- See Also:
- ClosedByInterruptException, AsynchronousCloseException, ClosedChannelException, NonWritableChannelException
- Geek's Notes:
- Description Add your codes or notes Search More Java Examples
[1684]How to write to a channel with a ByteBuffer
By verdana on 2005/12/06 19:06:17 Rate
try {
// Obtain a channel
WritableByteChannel channel =
new FileOutputStream ( "outfilename" ) .getChannel ( ) ;
// Create a direct ByteBuffer;
ByteBuffer buffer = 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 && buffer.hasRemaining ( ) ) {
buffer.put ( bytes [ index++ ] ) ;
}
// Set the limit to the current position and
// the position to 0 making the new bytes
// visible for write ( )
buffer.flip ( ) ;
// Write the bytes to the channel
int numWritten = channel.write ( buffer ) ;
// 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
buffer.compact ( ) ;
} else {
// Set the position to 0 and the limit to capacity
buffer.clear ( ) ;
}
}
// Close the file
channel.close ( ) ;
} catch ( Exception e ) {
e.printStackTrace ( ) ;
}