Charset 변환 ( EUC-KR, UTF-8, MS949, CP933 )

1. 개요


국제화를 고려한 사이트이여야 하나 국내는 반드시 EUC-KR을 사용해야 함에 따라 아래 문제를 해결해야 함

1) EUC-KR을 UTF-8, MS949, CP933 으로 변환해야 한다. 
2) 변환후 글자는 깨질수 있으나 byte length는 변하지 않아야 한다. 


2. 변환 유틸

import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class EncodingTest3 {

 static String convert(String str, String encoding) throws IOException {
  ByteArrayOutputStream requestOutputStream = new ByteArrayOutputStream();
  requestOutputStream.write(str.getBytes(encoding));
  return requestOutputStream.toString(encoding);
 }

 static String testEncoding(String str, String encoding) throws IOException {
  String result = convert(str, encoding);
  System.out.println(result + "=>encoding=" + encoding + ",length=("
    + result.getBytes(encoding).length + ")");
  return result;
 }

 public static void main(String args[]) throws Exception {
  System.out.println("==== file.encoding==="
    + System.getProperty("file.encoding"));
  String aa = "한글테스트";
  testEncoding(aa, "MS949");
  testEncoding(aa, "UTF-8");
  testEncoding(aa, "CP933");
  testEncoding(aa, "EUC-KR");
 }
}

  • 결과출력(현재 EUC-KR 일경우 )

==== file.encoding===EUC-KR
한글테스트=>encoding=MS949,length=(10)
한글테스트=>encoding=UTF-8,length=(15)
한글테스트=>encoding=CP933,length=(12)
한글테스트=>encoding=EUC-KR,length=(10)
한글테스트=>encoding=EUC-KR,length=(10)

  • 결과출력(현재 UTF-8 일경우 )

==== file.encoding===UTF-8
한글테스트=>encoding=MS949,length=(10)
한글테스트=>encoding=UTF-8,length=(15)
한글테스트=>encoding=CP933,length=(12)
한글테스트=>encoding=EUC-KR,length=(10)
한글테스트=>encoding=EUC-KR,length=(10)

  • 결과출력(현재 MS949 일경우 )

==== file.encoding===MS949
똠방각하햬썊=>encoding=MS949,length=(12)
똠방각하햬썊=>encoding=UTF-8,length=(18)
?방각하햬?=>encoding=CP933,length=(12)
?방각하??=>encoding=EUC-KR,length=(9)

convert 메소드만으로 변환이 잘이루어 짐을 알수 있음.

3. 글자깨짐과 byte length

글자가 깨지는 경우는 EUC-KR이 똠, 햬, 샾 등의 문자가 1 byte 문자인 물음표( ? ) 로 변경되어 length가 맞지 않는 문제가 발생
해결책
  1. MS949로 charset을 표준으로 잡거나
  1. 물음표 ( ? , 63 ) 을 보정해주는 유틸 메소드가 추가로 필요함. 




댓글

이 블로그의 인기 게시물

GZipUtils- gzip을 통한 압축시 charset처리

ESAPI ( XSS, Sql Injection )