read Long from ReadableByteChannel - Java java.nio.channels

Java examples for java.nio.channels:ReadableByteChannel

Description

read Long 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 long readLong(ReadableByteChannel channel)
            throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(8);
        if (fillBuffer(channel, buf, true)) {
            buf.rewind();/*w  w w .j a  v a 2 s  . c om*/
            return buf.getLong();
        }
        return -1L;
    }

    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