This Java tips illustrates a method of writing to a channel with a ByteBuffer. Developer may use a ByteBuffer to write to a channel. Output stream is used to write to a channel. 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;
        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) {
    }