write String to WritableByteChannel - Java java.nio.channels

Java examples for java.nio.channels:WritableByteChannel

Description

write String to WritableByteChannel

Demo Code


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

import java.nio.channels.WritableByteChannel;

public class Main {
    public static long writeString(WritableByteChannel channel, String val)
            throws IOException {
        int len = val.length();
        int size;
        ByteBuffer buf = ByteBuffer.allocate(size = 4 + 2 * len);
        buf.putInt(len);/*from w  ww.j a  va  2  s .  c  om*/
        for (int i = 0; i < len; i++) {
            buf.putChar(val.charAt(i));
        }
        buf.rewind();
        return writeByteBuffer(channel, buf, size);
    }

    /**
     * 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;
    }
}

Related Tutorials