=================================
=================================
=================================
출처: http://revf.tistory.com/84
CharCoding.java
package encodingtest;
import java.io.UnsupportedEncodingException;
/**
*
* @author Revfactory
*/
public class CharCoding {
public static String encode(String str, String charset) {
StringBuilder sb = new StringBuilder();
try {
byte[] key_source = str.getBytes(charset);
for(byte b : key_source) {
String hex = String.format("%02x", b).toUpperCase();
sb.append("%");
sb.append(hex);
}
} catch(UnsupportedEncodingException e) { }//Exception
return sb.toString();
}
public static String decode(String hex, String charset) {
byte[] bytes = new byte[hex.length()/3];
int len = hex.length();
for(int i = 0 ; i < len ;) {
int pos = hex.substring(i).indexOf("%");
if(pos == 0) {
String hex_code = hex.substring(i+1, i+3);
bytes[i/3] = (byte)Integer.parseInt(hex_code, 16);
i += 3;
} else {
i += pos;
}
}
try {
return new String(bytes, charset);
} catch(UnsupportedEncodingException e) { }//Exception
return "";
}
public static String changeCharset(String str, String charset) {
try {
byte[] bytes = str.getBytes(charset);
return new String(bytes, charset);
} catch(UnsupportedEncodingException e) { }//Exception
return "";
}
}
EncodingTest.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package encodingtest;
/**
*
* @author Minho
*/
public class EncodingTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String source = "대한민국";
System.out.println(source);
String hex_utf8 = CharCoding.encode(source, "UTF-8");
System.out.println(hex_utf8);
System.out.println(CharCoding.decode(hex_utf8, "UTF-8"));
String hex_euckr = CharCoding.encode(source, "EUC-KR");
System.out.println(hex_euckr);
System.out.println(CharCoding.decode(hex_euckr, "EUC-KR"));
System.out.println(CharCoding.changeCharset(source, "UTF-8"));
System.out.println(CharCoding.changeCharset(source, "EUC-KR"));
}
}
결과 :
대한민국
%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD
대한민국
%B4%EB%C7%D1%B9%CE%B1%B9
대한민국
대한민국
대한민국
=================================
=================================
=================================
'JAVA' 카테고리의 다른 글
[java] JAVA 자바 레지스트리(registry, 에디터:regedit) 값 불러오기 관련 (0) | 2012.05.18 |
---|---|
JAVA 자바 파일 인코딩 확인하기 관련 (0) | 2012.05.18 |
[java] 자바 스윙 타이머 (0) | 2011.09.29 |
자바 이클립스 한글 패치 방법 관련 (0) | 2011.08.12 |
[JAVA] 자바 OS 정보 (1) | 2011.04.18 |