read Int from ReadableByteChannel - Java java.nio.channels

Java examples for java.nio.channels:ReadableByteChannel

Description

read Int from ReadableByteChannel

Demo Code


//package com.java2s;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;

public class Main {
    public static int readInt(ReadableByteChannel channel)
            throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(4);
        if (fillBuffer(channel, buf, true)) {
            buf.rewind();/* w ww .  java 2 s . c  o m*/
            return buf.getInt();
        }
        return -1;
    }

    public static boolean fillBuffer(ReadableByteChannel channel,
            ByteBuffer buf, boolean clear) throws IOException {
        if (clear)
            buf.clear();

        while (true) {
            int cnt = channel.read(buf);
            if (cnt < 0)
                return false;
            if (buf.position() == buf.capacity())
                break;// fill to capacity
        }
        return true;
    }
}

Related Tutorials