Java Utililty Methods String Encode by Charset

List of utility methods to do String Encode by Charset

Description

The list of methods to do String Encode by Charset are organized into topic(s).

Method

StringcanEncode(String charset, CharSequence text, String unicodeValue)
can Encode
Charset cs;
try {
    cs = Charset.forName(charset);
} catch (IllegalCharsetNameException e) {
    return "Charset name '" + charset + "' is illegal.";
} catch (UnsupportedCharsetException e) {
    return "Charset '" + charset + "' is not supported.";
if (cs.canEncode() && cs.newEncoder().canEncode(text)) {
    return null;
return "Charset '" + charset + "' does not support encoding for \\u" + unicodeValue + ".";
booleancanEncode(String sz, String charset)
can Encode
try {
    Charset cs = Charset.forName(charset);
    if (cs.canEncode()) {
        CharsetEncoder cse = cs.newEncoder();
        return cse.encode(CharBuffer.wrap(sz)) != null;
    } else {
        return false;
} catch (Exception e) {
    return false;
CharsetcharsetForNameOrDefault(String encoding)
charset For Name Or Default
Charset charset = (encoding == null) ? Charset.defaultCharset() : Charset.forName(encoding);
return charset;
voidcheckEncoder(CharsetEncoder encoder)
check Encoder
if (encoder == null) {
    throw new IOException("Writer is closed");
byte[]deflate(int level, String str, Charset encoding)
deflate
byte[] bytes = str.getBytes(encoding);
Deflater def = new Deflater(level, true);
def.reset();
def.setInput(bytes);
def.finish();
byte[] buffer = getThreadBuffer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (!def.finished()) {
...
byte[]encode(Charset charset, String string)
encode
CharsetEncoder ce = charset.newEncoder();
int en = scale(string.length(), ce.maxBytesPerChar());
byte[] ba = new byte[en];
if (string.length() == 0)
    return ba;
ce.reset();
ByteBuffer bb = ByteBuffer.wrap(ba);
CharBuffer cb = CharBuffer.wrap(string);
...
Stringencode(final String str, final Charset charset)
encode
try {
    return URLEncoder.encode(str, charset.name());
} catch (UnsupportedEncodingException ex) {
    throw new RuntimeException(ex);
ByteBufferencode(String charsetName, char[] chars, int offset, int length)
encode
return encode(charsetName, CharBuffer.wrap(chars, offset, length));
Stringencode(String s, Charset encoding)

Escape a string into URI syntax

This function applies the URI escaping rules defined in section 2 of [RFC 2396], as amended by [RFC 2732], to the string supplied as the first argument, which typically represents all or part of a URI, URI reference or IRI.

if (s == null || s.isEmpty()) {
    return null;
int length = s.length();
int start = 0;
int i = 0;
StringBuilder result = new StringBuilder(length);
while (true) {
...
byte[]encode(String text, Charset charset)
encode
ByteBuffer buffer = charset.encode(text);
byte[] bytes = new byte[buffer.limit()];
buffer.get(bytes);
return bytes;