JAVA

[java] 자바 UTF-8, EUC-KR 인코딩 , 디코딩

AlrepondTech 2011. 10. 20. 14:31
반응형

 

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

 

출처: 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
대한민국
대한민국
대한민국

 

 

=================================

=================================

=================================

 

 

반응형