Better code for converting a char to its UTF-8 percent encoding representation? This is working code for a URI template (RFC 6570) implementation; when the character to render is not within a specific character set, it is needed to grab the UTF-8 representation of that character and encode each byte as a percent-encoded sequence.

The question is whether something more efficient than this exists?

private static String encodeChar(final char c)
{
    final String tmp = new String(new char[] { c });
    final byte[] bytes = tmp.getBytes(Charset.forName("UTF-8"));
    final StringBuilder sb = new StringBuilder();
    for (final byte b: bytes)
        sb.append('%').append(UnsignedBytes.toString(b, 16));
    return sb.toString();
}


Note: UnsignedBytes.toString() is from Guava.
Documentation here

public static void main(final String[] args) {
        try {
            System.out.println(URLEncoder.encode("a?&gt;éàùA-Z",
                    System.getProperty("sun.jnu.encoding")));
        } catch (final UnsupportedEncodingException e) {
            System.out.println("BIG PB");
            return; 
        }
    }


Output :


  a%3F%3E%E9%E0%F9A-Z


You have the same for URLEDecoder

EDIT

For URI
Found in src  of iMeMex Dataspace ManagementSystem

public static URI encode(String uriStr) throws URISyntaxException {
    if (uriStr != null) {
        // poor man's encoding
        uriStr = uriStr.replaceAll(" ", "%20");
    }
    return new URI(uriStr);
}


JavaDoc here

But URI from Java does not change other %VALUES.