read String from ReadableByteChannel - Java java.nio.channels

Java examples for java.nio.channels:ReadableByteChannel

Description

read String 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 String readString(ReadableByteChannel channel)
            throws IOException {
        int nameLen = readInt(channel); // name length
        if (nameLen < 0)
            return null;

        ByteBuffer buf = ByteBuffer.allocate(nameLen * 2);
        if (fillBuffer(channel, buf, true)) {
            char[] name = new char[nameLen];
            buf.rewind();/*w ww  .j  a va 2s. c om*/
            for (int i = 0; i < nameLen; i++) {
                name[i] = buf.getChar();
            }
            return new String(name);
        }
        return null;
    }

    public static int readInt(ReadableByteChannel channel)
            throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(4);
        if (fillBuffer(channel, buf, true)) {
            buf.rewind();
            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