Java Utililty Methods UTF8 Encode

List of utility methods to do UTF8 Encode

Description

The list of methods to do UTF8 Encode are organized into topic(s).

Method

byte[]encodeUTF8(String text)
encode UTF
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int i = 0; i < text.length(); i++) {
    char c = text.charAt(i);
    if (c != 0 && c < '\200') {
        baos.write(c);
    } else if (c == 0 || c >= '\200' && c < '\u0800') {
        baos.write((byte) (0xc0 | 0x1f & c >> 6));
        baos.write((byte) (0x80 | 0x3f & c));
...
StringencodeUtf8(String url)
encode Utf
try {
    return URLEncoder.encode(url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
    throw new RuntimeException("Unable to encode using charset");
BufferedWritergetBufferedWriter(final File outFile, final String outEncoding)
Create BufferedWriter object from specified file and encoding.
OutputStreamWriter osw;
if (outEncoding == null) {
    osw = new OutputStreamWriter(new FileOutputStream(outFile), Charset.defaultCharset());
} else {
    osw = new OutputStreamWriter(new FileOutputStream(outFile), outEncoding);
return new BufferedWriter(osw);
byte[]getUTF8Bytes(String string)
Returns the UTF8 bytes for string and handles the unlikely case where UTF-8 is not supported.
try {
    return string.getBytes("UTF-8");
} catch (UnsupportedEncodingException exc) {
    return string.getBytes();
byte[]getUTF8Bytes(String string)
Convert string to UTF-8 bytes
try {
    return string.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
    throw new IllegalStateException("UTF-8 encoding is not available", e);
CharsetDecodergetUTF8Decoder(boolean ignoreEncodingErrors)
get UTF Decoder
CodingErrorAction action = ignoreEncodingErrors ? CodingErrorAction.IGNORE : CodingErrorAction.REPORT;
return UTF8.newDecoder().onMalformedInput(action).onUnmappableCharacter(action);
intgetUTF8StringLength(String string)
Get length of UTF8 String Length
if (string == null) {
    return 0;
try {
    return string.getBytes("UTF-8").length;
} catch (UnsupportedEncodingException uee) {
return 0;
...
booleanisUTF8(String encoding)
is UTF
if (encoding == null)
    return true; 
int ret = Charset.forName(encoding).compareTo(Charset.forName("UTF-8"));
return ret == 0;
StringtoUTF8(byte[] bytes)
Convert to UTF-8 bytes
assert bytes != null;
String str = null;
try {
    str = new String(bytes, "utf-8"); 
} catch (UnsupportedEncodingException e) {
return str;
byte[]toUTF8(String content)
to UTF
try {
    return content.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
    throw new AssertionError("The world is coming to an end!  No UTF-8 support");