put Char Sequence to ByteBuffer - Java java.nio

Java examples for java.nio:ByteBuffer Char

Description

put Char Sequence to ByteBuffer

Demo Code

/*//from  w ww . j  a  va2  s.  c om
 * Copyright (C) 2008-2010 Wayne Meissner
 *
 * This file is part of the JNR project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;

public class Main {
    public static void putCharSequence(ByteBuffer buf, Charset charset,
            CharSequence value) {
        putCharSequence(buf, charset.newEncoder(), value);
    }

    public static void putCharSequence(ByteBuffer buf,
            CharsetEncoder encoder, CharSequence value) {
        // 
        // Convert any CharSequence implementor (String, etc) into a native
        // C string.
        //
        encoder.reset().onMalformedInput(CodingErrorAction.REPLACE)
                .onUnmappableCharacter(CodingErrorAction.REPLACE)
                .encode(CharBuffer.wrap(value), buf, true);
        encoder.flush(buf);
        final int nulSize = Math.round(encoder.maxBytesPerChar());
        // NUL terminate the string
        if (nulSize == 4) {
            buf.putInt(0);
        } else if (nulSize == 2) {
            buf.putShort((short) 0);
        } else if (nulSize == 1) {
            buf.put((byte) 0);
        }
    }
}

Related Tutorials