Here you can find the source of unicodeCodePoint2PercentHexString(int codePoint, String charsetName)
Parameter | Description |
---|---|
codePoint | the given Unicode code point |
charsetName | the name of the character set. |
Parameter | Description |
---|---|
IllegalArgumentException | if the code point is not defined or the the character set is not supported. |
public static String unicodeCodePoint2PercentHexString(int codePoint, String charsetName)
//package com.java2s; import java.nio.charset.Charset; import java.nio.charset.CharacterCodingException; import java.nio.CharBuffer; import java.nio.ByteBuffer; public class Main { /**//ww w. ja v a 2 s. co m * Return the percentHexOctets string that represents the given Unicode * code point in the given character set or null if the given character * set cannot encode the given code point. * * @param codePoint the given Unicode code point * @param charsetName the name of the character set. * @return the percentHexOctets string that represents the given Unicode code point in the given character set. * @throws IllegalArgumentException if the code point is not defined or the the character set is not supported. */ public static String unicodeCodePoint2PercentHexString(int codePoint, String charsetName) { if (!Character.isDefined(codePoint)) throw new IllegalArgumentException( "Not a valid Unicode code point [" + codePoint + "]."); Charset charset = Charset.availableCharsets().get(charsetName); if (charset == null) throw new IllegalArgumentException("Unsupported charset [" + charsetName + "]."); char[] chars = Character.toChars(codePoint); ByteBuffer byteBuffer = null; try { byteBuffer = charset.newEncoder() .encode(CharBuffer.wrap(chars)); } catch (CharacterCodingException e) { // The selected charset cannot encode given code point. return null; } byteBuffer.rewind(); StringBuilder encodedString = new StringBuilder(); for (int i = 0; i < byteBuffer.limit(); i++) { String asHex = Integer.toHexString(byteBuffer.get() & 0xFF); encodedString.append("%") .append(asHex.length() == 1 ? "0" : "").append(asHex); } return encodedString.toString(); } }