Here you can find the source of stringToBytes(final String inString)
Parameter | Description |
---|---|
inString | String to be converted |
public static byte[] stringToBytes(final String inString)
//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; } }