Java Byte Array to String by Charset toString(byte[] bytes, String charsetName)

Here you can find the source of toString(byte[] bytes, String charsetName)

Description

Constructs a new String by decoding the given bytes using the specified charset.

License

Apache License

Parameter

Parameter Description
bytes the bytes to be decoded into characters
charsetName the name of a supported java.nio.charset.Charset charset

Return

the decoded String

Declaration

public static String toString(byte[] bytes, String charsetName) 

Method Source Code

//package com.java2s;
/*/*from   w w  w  . ja va 2s. com*/
 * Copyright 2011 Google Inc.
 * Copyright 2014 Andreas Schildbach
 *
 * 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;

public class Main {
    /**
     * Constructs a new String by decoding the given bytes using the specified charset.
     * <p>
     * This is a convenience method which wraps the checked exception with a RuntimeException.
     * The exception can never occur given the charsets
     * US-ASCII, ISO-8859-1, UTF-8, UTF-16, UTF-16LE or UTF-16BE.
     *
     * @param bytes the bytes to be decoded into characters
     * @param charsetName the name of a supported {@linkplain java.nio.charset.Charset charset}
     * @return the decoded String
     */
    public static String toString(byte[] bytes, String charsetName) {
        try {
            return new String(bytes, charsetName);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. toCharSet(byte[] bytes, String fromCharsetName, String toCharsetName)
  2. toDebugString(final byte[] bytes, final int len, final Charset charset)
  3. toEncodedString(byte[] bytes, Charset charset)
  4. toString(byte[] b, String charset)
  5. toString(byte[] bytes, Charset charset)
  6. toString(byte[] data, int from, int length, Charset charset)
  7. toString(final byte[] bytes, final String charsetName)
  8. toUnicode(byte[] isoStr, String charset)
  9. truncateByByteLength(String string, int maxBytes, Charset charset)