자바 유니코드 변환(encode, decode)
2016-11-14
인터넷에 돌아다니는 소스를 다소 수정하여 만들었음. by bb_
public static void main(String[] args) {
try {
System.out.println(encode(“동해물과 백두산이 마르고 닳도록,”));
System.out.println(decode(“\ub3d9\ud574\ubb3c\uacfc \ubc31\ub450\uc0b0\uc774 \ub9c8\ub974\uace0 \ub2f3\ub3c4\ub85d\u002c”));
System.out.println(decode(encode(“동해물과 백두산이 마르고 닳도록,”)));
}catch (Exception e) {
e.printStackTrace();
}
}
public static String decode(String unicodeStr) throws Exception {
StringBuffer str = new StringBuffer();
int i = -1;
char ch = 0;
String decodeStr = “”;
int nextBegin = -1;
while ((i = unicodeStr.indexOf(“\\u“)) > -1) {
if (i + 6 > unicodeStr.length()) {
// 유니코드 값이 길이가 4자리가 안된다면 변환 무시
decodeStr = “\\u” + unicodeStr.substring(i + 2);
nextBegin = unicodeStr.length();
} else {
try {
ch = (char)Integer.parseInt(unicodeStr.substring(i + 2, i + 6), 16);
decodeStr = String.valueOf(ch);
nextBegin = i + 6;
} catch (NumberFormatException e) {
// 유니코드 값이 16진수 포맷이 아니라면 변환 무시
decodeStr = “\\u” + unicodeStr.substring(i + 2, i + 6);
nextBegin = i + 6;
}
}
str.append(unicodeStr.substring(0, i));
str.append(decodeStr);
unicodeStr = unicodeStr.substring(nextBegin);
}
str.append(unicodeStr);
return str.toString();
}
public static String encode(String orgStr) throws Exception {
StringBuffer str = new StringBuffer();
int len = orgStr.length();
for (int i = 0; i < len; i++) {
if (((int)orgStr.charAt(i) == 32)) {
str.append(” “);
continue;
}
str.append(“\\u“);
String hexCode = Integer.toHexString((int)orgStr.charAt(i));
int space = 4 – hexCode.length();
for(int k=0; k<space; k++) {
str.append(“0”);
}
str.append(hexCode);
}
return str.toString();
}