public static String encodeHtmlEntities(String input, String encoding) {

        StringBuffer result = new StringBuffer(input.length() * 2);
        CharBuffer buffer = CharBuffer.wrap(input.toCharArray());
        Charset charset = Charset.forName(encoding);
        CharsetEncoder encoder = charset.newEncoder();
        for (int i = 0; i < buffer.length(); i++) {
            int c = buffer.get(i);
            if (c < 128) {
                // first 128 chars are contained in almost every charset
                result.append((char)c);
                // this is intended as performance improvement since
                // the canEncode() operation appears quite CPU heavy
            } else if (encoder.canEncode((char)c)) {
                // encoder can encode this char
                result.append((char)c);
            } else {
                // append HTML entity reference
                result.append(ENTITY_PREFIX);
                result.append(c);
                result.append(";");
            }
        }
        return result.toString();
    }
public static String encodeHtmlEntities ( String input , String encoding ) { StringBuffer result = new StringBuffer ( input . length ( ) * 2 ) ; CharBuffer buffer = CharBuffer . wrap ( input . toCharArray ( ) ) ; Charset charset = Charset . forName ( encoding ) ; CharsetEncoder encoder = charset . newEncoder ( ) ; for ( int i = 0 ; i < buffer . length ( ) ; i ++ ) { int c = buffer . get ( i ) ; if ( c < 128 ) { result . append ( ( char ) c ) ; } else if ( encoder . canEncode ( ( char ) c ) ) { result . append ( ( char ) c ) ; } else { result . append ( ENTITY_PREFIX ) ; result . append ( c ) ; result . append ( ";" ) ; } } return result . toString ( ) ; }
Encodes all characters that are contained in the String which can not displayed
in the given encodings charset with HTML entity references
like <code>&amp;#8364;</code>.<p>

This is required since a Java String is
internally always stored as Unicode, meaning it can contain almost every character, but
the HTML charset used might not support all such characters.<p>

@param input the input to encode for HTML
@param encoding the charset to encode the result with

@return the input with the encoded HTML entities

@see #decodeHtmlEntities(String, String)