본문 바로가기

Java

[JAVA] getBytes()와 String생성자로 인코딩 디코딩하기

String class에는 getBytes() 메서드를 사용해 문자열을 인코딩할 수 있다.  다만 플랫폼의 기본 charset에 없으면 변환 불가능하다.   

 

문자열을 byte[]로 인코딩하면 디코딩할 때에도 같은 charset을 사용해 주어야 한다. 만약 다른 charset을 사용하면 외계어를 볼 수 있을 것이다.

public class Test {

	public static void main(String[] args) throws UnsupportedEncodingException  {
		String str = "가나다라마바사";
		String decode = null;
		byte[] encode = null;
		
		encode = str.getBytes("UTF-8");
		for (byte b : encode) {
			System.out.print(String.format("%X ", b));	
		}
		System.out.println();
		
		decode = new String(encode, "UTF-8");
		System.out.println(decode);
			
    }

}

  

 

위에서 UTF-8로 인코딩된 바이트배열을 EUC-KR로 디코딩하면 이런 끔찍한 문자를 볼 수 있다. 

媛����ㅻ�쇰�諛���

 

'Java' 카테고리의 다른 글

[Java] Wrapper Class  (0) 2023.06.21
[자바] 쉬프트 연산자  (0) 2023.06.15
getClass()  (0) 2023.06.09
clone 메서드의 문제점 (얕은 복사, 깊은 복사)  (0) 2023.06.07
자바 내 코드 성능 테스트 방법  (1) 2023.06.06