인코딩에 관한 애기를 하고자한다.
1. 인코딩이란 무엇인가?
    컴퓨터가 알고있는 문자는 0,1 이 두가지 밖에 없다. 그런데 사람이 쓰는 문자는 영어, 한글, 일본어 등...
    엄청 많다. 그러면 사람이 쓰는 문자를 컴퓨터가 알아먹게 하기위해서 0, 1로 바꿔줘야된다.
    그 바꿔주는 규칙을 정의해놓은것이 바로 인코딩이다. 인코딩중에 대표적인게 ascii 코드다.  ascii 코드는 http://www.asciitable.com/ 여기서 확인가능하다. 그런데 이 ascii 코드는 1Byte로 구성되어 있다. 1Byte로는 각국의 언어를 다 담을수 없어서 2Byte짜리 Unicode를 만들어 냈다. 어..그런데 ascii로도 한글이 표현이 가능한데?
물론 가능하다.. 그렇지만 다른 나라에서는 호환되게 사용할수가 없다. 세계 각국의 언어를 다 담을려면 1Byte로는 모자르기 때문에 2Byte로된 Unicode를 만들어 낸것이다. 이 유니코드에 대한 애기는 하지 않겠다.

2. 보여지는 글자와 컴퓨터가 인식하는 문자는 다르다
 UltraEdit에서 ascii 코드로 문자를 입력하는 경우와 unicode로 문자를 입력하는 경우 어떻게 변환되는지 보도록하자.
사용자 삽입 이미지

ascii 코드


사용자 삽입 이미지
위에 그림은 ascii 변환되었을 때의 값이고 아래 그림은 unicode로 변환되었을 때의 값이다.
같은 문자를 입력했지만 인코딩 방식에 따라서 변환되는 값은 달라지게된다.
보통 문자가 깨지는 경우는 여러가지 경우가 있겠지만 이 인코딩이 안맞아서 그런것이 대부분이다.

3. 자바에서 인코딩을 변환하는 방법
package encodingTest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class MyEncoding {
   
    public void convertCharSet(String fromCharset, String toCharset){
        InputStreamReader iReader = null;
        OutputStreamWriter oWriter = null;
        try {
            String asciiPath = "files/encoding/asciiSample.txt";
            String outUnicodePath = "files/encoding/asciiSample_out.txt";
            String inputEncoding = "US-ASCII";
            String outputEncoding = "UTF-16LE";
            iReader = new InputStreamReader(
                    new FileInputStream(asciiPath), inputEncoding);
            oWriter = new OutputStreamWriter(
                    new FileOutputStream(outUnicodePath), outputEncoding);
            int c;
            char[] charBuf = new char[1024];
            while((c = iReader.read(charBuf)) != -1){
                oWriter.write(charBuf, 0, c);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                iReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                oWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

Posted by 즐건세상
l