Java UTF8 Encode toUTF8(String str)

Here you can find the source of toUTF8(String str)

Description

Converts the string to a UTF-8 byte array, turning the checked exception (which should never happen) into a runtime exception.

License

Apache License

Declaration

public static byte[] toUTF8(String str) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.io.UnsupportedEncodingException;

public class Main {
    /**//  w  w  w  .j  ava2 s  . com
     *  Converts the string to a UTF-8 byte array, turning the checked exception
     *  (which should never happen) into a runtime exception.
     *  <p>
     *  If passed <code>null</code>, returns an empty array.
     */
    public static byte[] toUTF8(String str) {
        try {
            if (str == null)
                return new byte[0];

            return str.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 not supported", e);
        }
    }
}

Related

  1. toUTF8(byte[] bytes)
  2. toUTF8(String content)
  3. toUTF8(String isoString)
  4. toUTF8(String s)
  5. toUTF8(String sourceStr)
  6. toUtf8(String str)
  7. toUTF8(String str)
  8. toUTF8(String str)
  9. toUTF8(String string)