Here you can find the source of forceEncoding(String inputString, String targetCharset)
Parameter | Description |
---|---|
inputString | Input string. |
targetCharset | Charset to use for conversion, e.g. UTF-8 |
Parameter | Description |
---|---|
CharacterCodingException | an exception |
public static String forceEncoding(String inputString, String targetCharset) throws CharacterCodingException
//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; } }