Java Byte Array to String by Charset asBytes(String string, Charset charset)

Here you can find the source of asBytes(String string, Charset charset)

Description

Turn a string into an array of bytes using the passed Charset

License

Apache License

Parameter

Parameter Description
string a parameter
charset a parameter

Return

a byte[] array

Declaration

public static byte[] asBytes(String string, Charset charset) 

Method Source Code


//package com.java2s;
/*//w w  w  . jav a2 s.  c  o  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 {
    /**
     * 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. bytesToString(byte[] bytes, Charset charset)
  2. byteToString(byte[] b, String charset)
  3. byteToString(Charset charset, byte[] data)
  4. changeEncoding(byte[] byteArray, Charset charsetFrom, Charset charsetTo)