Java Byte Array to String by Charset changeEncoding(byte[] byteArray, Charset charsetFrom, Charset charsetTo)

Here you can find the source of changeEncoding(byte[] byteArray, Charset charsetFrom, Charset charsetTo)

Description

Usage: Charset charsetFrom = Charset.forName("UTF-8"); Charset charsetTo = Charset.forName("ISO-8859-15");

License

Open Source License

Parameter

Parameter Description
charsetFrom a parameter
charsetTo a parameter

Declaration

public static byte[] changeEncoding(byte[] byteArray, Charset charsetFrom, Charset charsetTo) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009 Daniel Murygin <dm[at]sernet[dot]de>.
 * This program is free software: you can redistribute it and/or 
 * modify it under the terms of the GNU Lesser General Public License 
 * as published by the Free Software Foundation, either version 3 
 * of the License, or (at your option) any later version.
 *     This program is distributed in the hope that it will be useful,    
 * but WITHOUT ANY WARRANTY; without even the implied warranty 
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU Lesser General Public License for more details.
 *     You should have received a copy of the GNU Lesser General Public 
 * License along with this program. /*from  w  w w .  ja  va 2  s. c  o m*/
 * If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Daniel <dm[at]sernet[dot]de> - initial API and implementation
 ******************************************************************************/

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class Main {
    /**
     * Usage: Charset charsetFrom = Charset.forName("UTF-8"); Charset charsetTo
     * = Charset.forName("ISO-8859-15");
     * 
     * 
     * @param charsetFrom
     * @param charsetTo
     * @return
     */
    public static byte[] changeEncoding(byte[] byteArray, Charset charsetFrom, Charset charsetTo) {
        ByteBuffer inputBuffer = ByteBuffer.wrap(byteArray);
        // decode charsetFrom
        CharBuffer data = charsetFrom.decode(inputBuffer);
        // encode charsetTo
        ByteBuffer outputBuffer = charsetTo.encode(data);
        return outputBuffer.array();
    }
}

Related

  1. asBytes(String string, Charset charset)
  2. bytesToString(byte[] bytes, Charset charset)
  3. byteToString(byte[] b, String charset)
  4. byteToString(Charset charset, byte[] data)
  5. charSequence2Bytes(CharSequence sb, Charset charset)
  6. charSetForBOM(byte[] buffer, int offset)
  7. convertCharset(byte[] content, Charset fromCharset, Charset toCharset)
  8. convertToBytes(final String str, final Charset charset)