Java InputStream Read by Charset forceEncoding(String inputString, String targetCharset)

Here you can find the source of forceEncoding(String inputString, String targetCharset)

Description

Converts a given string to use the given encoding, e.g.

License

Open Source License

Parameter

Parameter Description
inputString Input string.
targetCharset Charset to use for conversion, e.g. UTF-8

Exception

Parameter Description
CharacterCodingException an exception

Declaration

public static String forceEncoding(String inputString, String targetCharset) throws CharacterCodingException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**/*from   w w  w.  j av a2s. c om*/
     * Converts a given string to use the given encoding, e.g. UTF-8. Replaces non-compliant chracters with a space i.e. " "
     * @param inputString Input string.
     * @param targetCharset Charset to use for conversion, e.g. UTF-8
     * @return
     * @throws CharacterCodingException
     */
    public static String forceEncoding(String inputString, String targetCharset) throws CharacterCodingException {

        String returnString = "";

        Charset charset = Charset.forName(targetCharset);
        CharsetDecoder decoder = charset.newDecoder();
        CharsetEncoder encoder = charset.newEncoder();

        // Replace non-compliant characters with " "
        encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
        encoder.replaceWith(" ".getBytes());

        // Convert the string to targetCharset bytes in a ByteBuffer
        ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(inputString));

        // Convert bytes in a ByteBuffer to a character ByteBuffer and then back to a string.
        CharBuffer cbuf = decoder.decode(bbuf);
        returnString = cbuf.toString();

        return returnString;
    }
}

Related

  1. convertStreamToString(final InputStream is, final Charset charset)
  2. convertToCharacterSet(byte[] input, Charset fromCharset, Charset toCharSet)
  3. copyToString(InputStream in, Charset charset)
  4. createInput(String s, String charsetName)
  5. createZipInputStream(InputStream inStream, Charset charset)
  6. fromUnicode(String charset, String input)
  7. getContentFromInputStream(InputStream in, String charset)
  8. getHeaderLen(FileInputStream in, Charset encoding)
  9. getInputCharset()