web developer

[java] character set 이해하기 [HTML Encoding] 본문

Language/Java

[java] character set 이해하기 [HTML Encoding]

trueman 2023. 10. 9. 22:38
728x90
728x90

디폴트 캐릭터셋 확인

System.out.println(System.getProperty("file.encoding")); //UTF-8

(1) new String(strs1)

strs1이라는 문자열을 복사하여 새로운 문자열 객체를 만듭니다.

String strs1 = "인코딩1";
String convert1 = new String(strs1);   
System.out.println("Value  : " + convert1); //Value  : 인코딩1
System.out.println();

(2) new String(strs2.getBytes()) 

디폴트 캐릭터셋으로 바이트 배열이 리턴된다.

String strs2 = "인코딩2";
String convert2 = new String(strs2.getBytes());
System.out.println("Value  : " + convert2); //Value  : 인코딩2
System.out.println();

(3) new String(strs3.getBytes("utf-8")) 

'strs3' 문자열을 'utf-8' 인코딩으로 변환한 바이트 배열을 생성하고, 이 바이트 배열을 사용하여 새로운 문자열을 생성

String strs3 = "인코딩3";
String convert3 = new String(strs3.getBytes("utf-8"));
System.out.println("Value  : " + convert3); //Value  : 인코딩3
System.out.println();

(4) new String(strs4.getBytes("euc-kr"))

'strs4' 문자열을 'euc-kr' 인코딩으로 변환한 바이트 배열을 생성하고, 이 바이트 배열을 사용하여 새로운 문자열을 생성
→ 이는 String의 두 번째 파라메터로 넣는 캐릭터 셋을 '바이트 배열의 캐릭터 셋'이 아닌 '다른 캐릭터셋'을 넣어 변환하겠다는 의미인데, 이 자린 바이트 배열에 저장된 바이트들의 캐릭터 셋을 설정하는 곳이다.

 올바르지 못한 설정

String strs4 = "인코딩4";
String convert4 = new String(strs4.getBytes("euc-kr"));
System.out.println("Value  : " + convert4); //Value  : ���ڵ�4
System.out.println();

(5) new String(strs5.getBytes("euc-kr"), "utf-8")

'euc-kr' 라는 캐릭터 셋으로 바이트 배열을 읽어들인 다음 'utf-8'이라는 새로운 캐릭터셋으로 변환(?)을 시도하겠다는 것이다.

올바르지 못한 설정

String strs5 = "인코딩5";
String convert5 = new String(strs5.getBytes("euc-kr"), "utf-8");
System.out.println("Value  : " + convert5); //Value  : ���ڵ�5
System.out.println();

(6) new String(strs6.getBytes("utf-8"), "euc-kr")

'utf-8' 라는 캐릭터 셋으로 바이트 배열을 읽어들인 다음 'euc-kr'이라는 새로운 캐릭터셋으로 변환(?)을 시도하겠다는 것이다.

 올바르지 못한 설정

String strs6 = "인코딩6";
String convert6 = new String(strs6.getBytes("utf-8"), "euc-kr");
System.out.println("Value  : " + convert6); //Value  : �몄���6
System.out.println();

(7) for문을 통해 한번에 인코딩 체크하기

// 한글이 저장된 경우 같은 계열(변환가능한)의 캐릭터 셋이 아니라면 100% 결과가 깨지게 된다.
String originalStr = "테스트"; // String 객체 생성 
byte[] bytes2 = originalStr.getBytes("utf-8"); // 바이트 배열에 저장 
originalStr = new String(bytes2);

String[] charSet = {"utf-8", "euc-kr", "ksc5601", "iso-8859-1", "x-windows-949"};
for(int i = 0; i<charSet.length; i++){
    for(int j = 0; j<charSet.length; j++){
        try{ 
            System.out.println("[" + charSet[i] + "," + charSet[j] + "]" + new String(originalStr.getBytes(charSet[i]), charSet[j]));
        } catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }
}

https://kin.naver.com/knowhow/detail.nhn?docId=527939 

https://d2.naver.com/helloworld/19187

https://d2.naver.com/helloworld/76650

https://codingpractices.tistory.com/entry/%EC%9D%B8%EC%BD%94%EB%94%A9-vs-%EB%94%94%EC%BD%94%EB%94%A9-%EC%A0%95%ED%99%95%ED%95%98%EA%B2%8C-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0

728x90
728x90
Comments