Java examples for java.nio.channels:WritableByteChannel
write Int to WritableByteChannel
//package com.java2s; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; public class Main { public static long writeInt(WritableByteChannel channel, int val) throws IOException { ByteBuffer buf = ByteBuffer.allocate(4); buf.putInt(val); buf.rewind();//from w ww . j a v a 2 s . c o m return writeByteBuffer(channel, buf, 4); } /** * Writes bytes from buf to the channel until at least bytesToWrite number of bytes are written. * @param channel the destination channel * @param buf the source buffer * @param t the number of bytes to write * @return the number of bytes written * @throws IOException */ private static int writeByteBuffer(WritableByteChannel channel, ByteBuffer buf, int bytesToWrite) throws IOException { int t = bytesToWrite; // remaining bytes to write while (t > 0) { t -= channel.write(buf); } return bytesToWrite - t; } }