Java Byte Array to String by Charset toCharSet(byte[] bytes, String fromCharsetName, String toCharsetName)

Here you can find the source of toCharSet(byte[] bytes, String fromCharsetName, String toCharsetName)

Description

to Char Set

License

Apache License

Declaration

public static byte[] toCharSet(byte[] bytes, String fromCharsetName, String toCharsetName)
        throws UnsupportedEncodingException 

Method Source Code

//package com.java2s;
/*/*from  w  w w . j a va2  s  .  com*/
 * Copyright 2013 Primeton.
 *
 * 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.CharBuffer;

import java.nio.charset.Charset;

public class Main {

    public static byte[] toCharSet(byte[] bytes, String fromCharsetName, String toCharsetName)
            throws UnsupportedEncodingException {
        if (bytes == null) {
            throw new IllegalArgumentException("bytes is null!");
        }
        if (toCharsetName == null || toCharsetName.trim().length() == 0) {
            throw new IllegalArgumentException("toCharsetName is null!");
        }
        if (fromCharsetName == null || fromCharsetName.trim().length() == 0) {
            fromCharsetName = System.getProperty("file.encoding");
        }
        return new String(bytes, fromCharsetName).getBytes(toCharsetName);
    }

    public static String toCharSet(String str, String charsetName) throws UnsupportedEncodingException {
        if (str == null || str.trim().length() == 0) {
            throw new IllegalArgumentException("str is null!");
        }
        if (charsetName == null || charsetName.trim().length() == 0) {
            throw new IllegalArgumentException("charsetName is null!");
        }
        return new String(Charset.forName(charsetName).encode(CharBuffer.wrap(str)).array(), charsetName);
    }
}

Related

  1. str(byte[] bytes, String charset)
  2. stringToByteArray(String str, Charset charsetForEncoding, int lenOfByteArray, byte filler)
  3. toBytes(CharSequence str, String charsetName)
  4. toBytes(String string, Charset charset)
  5. toChars(byte[] b, String charset)
  6. toDebugString(final byte[] bytes, final int len, final Charset charset)
  7. toEncodedString(byte[] bytes, Charset charset)
  8. toString(byte[] b, String charset)
  9. toString(byte[] bytes, Charset charset)