Java Convert via ByteBuffer stringToBytes(final String inString)

Here you can find the source of stringToBytes(final String inString)

Description

Converts a String to UTF-8 bytes.

License

Apache License

Parameter

Parameter Description
inString String to be converted

Return

Bytes of inString

Declaration

public static byte[] stringToBytes(final String inString) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;

public class Main {
    /**//from   w  w  w . ja  v a  2s  . co m
     * Converts a String to UTF-8 bytes.
     *
     * @param inString String to be converted
     * @return Bytes of inString
     */
    public static byte[] stringToBytes(final String inString) {
        final CharsetEncoder enc = Charset.forName("UTF-8").newEncoder();
        enc.onMalformedInput(CodingErrorAction.REPORT);
        enc.onUnmappableCharacter(CodingErrorAction.REPORT);
        final CharBuffer cb = CharBuffer.wrap(inString);
        ByteBuffer bb;
        try {
            bb = enc.encode(cb);
        } catch (final CharacterCodingException e) {
            return inString.getBytes();
        }
        final byte[] ba1 = bb.array();
        final byte[] ba2 = new byte[bb.limit()];
        System.arraycopy(ba1, 0, ba2, 0, ba2.length);
        return ba2;
    }
}

Related

  1. longToShorts2(long value)
  2. shortToByteArray(short inShort)
  3. shortToBytes(short s)
  4. stringsFromBinary(final byte[] binary)
  5. stringsToBinary(final String strings[])
  6. stringToBytes(String str)
  7. StringToData(String conv, boolean isRe, int number)
  8. stringToIpAddress(String s)
  9. stringToLong(String offsetString)