Java UTF8 Convert To getBytesUtf8(String string)

Here you can find the source of getBytesUtf8(String string)

Description

Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte array.

License

Apache License

Parameter

Parameter Description
string the String to encode, may be <code>null</code>

Exception

Parameter Description
IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.

Return

encoded bytes, or null if the input string was null

Declaration

public static byte[] getBytesUtf8(String string) 

Method Source Code


//package com.java2s;
/*/*from  ww  w . j a  v  a  2 s  .  c o m*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.UnsupportedEncodingException;

public class Main {
    /**
     * Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte
     * array.
     * 
     * @param string
     *            the String to encode, may be <code>null</code>
     * @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
     * @throws IllegalStateException
     *             Thrown when the charset is missing, which should be never according the the Java specification.
     * @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
     * @since Commons Checksum 1.0
     */
    public static byte[] getBytesUtf8(String string) {
        if (string == null) {
            return null;
        }
        try {
            return string.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("UTF-8 : " + e);
        }
    }
}

Related

  1. fromUTF8(byte[] bytes)
  2. fromUTF8Bytes(byte[] bytes)
  3. fromUTF8Bytes(byte[] bytes)
  4. getBytesUtf8(String str)
  5. getBytesUTF8(String string)
  6. getBytesUtf8(String string)
  7. getBytesUtf8(String string)
  8. UTF8ToCodePoint(byte[] b, int s)
  9. utf8ToCodePoint(int b1, int b2, int b3, int b4)