Here you can find the source of string2BytesUTF8(String str)
public static byte[] string2BytesUTF8(String str)
//package com.java2s; public class Main { private static byte[] outputByte = new byte[3]; public static byte[] string2BytesUTF8(String str) { byte[] bufByte = new byte[str.length() * 3]; int byteLen = char2ByteUTF8(str, 0, str.length(), bufByte, 0, bufByte.length, false);//from w w w .j av a2 s . c o m byte[] ret = new byte[byteLen]; System.arraycopy(bufByte, 0, ret, 0, byteLen); return ret; } public static int char2ByteUTF8(String input, int inOff, int inEnd, byte[] output, int outOff, int outEnd, boolean getLengthFlag) { char inputChar; int outputSize; int charOff = inOff; int byteOff = outOff; while (charOff < inEnd) { inputChar = input.charAt(charOff); if (inputChar < 0x80) { outputByte[0] = (byte) inputChar; outputSize = 1; } else if (inputChar < 0x800) { outputByte[0] = (byte) (0xc0 | ((inputChar >> 6) & 0x1f)); outputByte[1] = (byte) (0x80 | (inputChar & 0x3f)); outputSize = 2; } else { outputByte[0] = (byte) (0xe0 | ((inputChar >> 12)) & 0x0f); outputByte[1] = (byte) (0x80 | ((inputChar >> 6) & 0x3f)); outputByte[2] = (byte) (0x80 | (inputChar & 0x3f)); outputSize = 3; } if (getLengthFlag) { byteOff += outputSize; } else { if ((byteOff + outputSize) > outEnd) { return -1; } for (int i = 0; i < outputSize; i++) { output[byteOff++] = outputByte[i]; } } charOff++; } return byteOff - outOff; } }