Java UTF8 utf8StringToBytes(String string)

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

Description

Turn a UTF-8 encoded string into an array of bytes

License

Apache License

Parameter

Parameter Description
string a parameter

Return

the bytes for the supplied String

Declaration

public static byte[] utf8StringToBytes(String string) 

Method Source Code


//package com.java2s;
/*//www . j av  a 2 s. co m
 * Licensed 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;
import java.nio.charset.Charset;

public class Main {
    public static Charset UTF_8 = Charset.forName("UTF-8");

    /**
     * Turn a UTF-8 encoded string into an array of bytes
     * 
     * @param string
     * @return the bytes for the supplied String
     */
    public static byte[] utf8StringToBytes(String string) {
        return asBytes(string, UTF_8);
    }

    /**
     * Turn a string into an array of bytes using the passed {@link Charset}
     * 
     * @param string
     * @param charset
     * @return a byte[] array
     */
    public static byte[] asBytes(String string, Charset charset) {
        if (string == null) {
            return null;
        }

        if (charset == null) {
            throw new IllegalArgumentException("Cannot get bytes without a Charset");
        }

        try {
            return string.getBytes(charset.name());
        } catch (UnsupportedEncodingException e) {
            //since we are using *actual* charsets, not string lookups, this
            //should *never* happen. But it is better to throw it up than swallow it.
            throw new IllegalStateException("Charset present", e);
        }
    }
}

Related

  1. utf8SafeCEscape(String src)
  2. utf8String(String... strs)
  3. utf8StringLength(final CharSequence sequence)
  4. utf8StringSizeInBytes(String s)
  5. utf8StringToByteArray(String dataString)
  6. utf8ToString(byte[] data)
  7. utf8URLDecode(String input)
  8. utf8urldecode(String text)
  9. Utf8URLencode(String text)