Notice
Recent Posts
Recent Comments
Link
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Tags more
Archives
Today
Total
관리 메뉴

jeongwon

[method] String.getBytes() & charset 본문

JAVA

[method] String.getBytes() & charset

jeongwon_ 2022. 6. 4. 16:27

getBytes()

문자열을 default charset 형식으로 인코딩하고, 그 결과를 새 바이트 배열(byte[])에 저장하는 메소드이다.

 

String (Java SE 18 & JDK 18)

All Implemented Interfaces: Serializable, CharSequence, Comparable , Constable, ConstantDesc The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constan

docs.oracle.com

 


charset

charset = "coded character set"
"컴퓨터에서 문자를 표현하기 위해, 각 문자를 정수값에 대응시켜 놓은 체계"

(출처: https://www.pmguda.com/563 )

 

HTML <head> 태그에 위치한 <meta charset="utf-8"> 의 "utf-8"이 대표적이다. 

"utf-8"은 유니코드를 이용한 인코딩 방식으로 대부분의 사전적 문자를 표기할 수 있게 한다. 

(출처: https://hyoje420.tistory.com/3 )

 


돌아가서, getBytes() 메소드가 기준으로 삼는 인코딩 방식(default charset) 은

- 인자를 통해 전달된 인코딩 방식이 없다면

- JVM 설정을 따르고, JVM 설정을 따로 해주지 않으면

- 일반적으로 JVM의 기본 Charset으로 설정된 windows-1252  UNIX, UTF-8 방식을 따른다.(window기준)

(출처: https://choiseonjae.github.io/java/getbytes/encoding, 

https://www.ibm.com/docs/ko/ibm-mq/9.1?topic=conversion-jms-client-message-encoding)

 


 

 

 

 

String 생성자에는 아래와 같은 유형이 있다. 지정한 문자셋으로 디코딩해준다. 

public String(byte[] bytes, String charsetName)
       throws UnsupportedEncodingException

 

이를 이용해 getBytes()를 이용한 간단한 코드들을 비교해 보면

 

import java.io.UnsupportedEncodingException;

public class Main{

	public static void main(String[] args) throws UnsupportedEncodingException {
		String str = "ABC\\";
		String name = "정원";
		String ecname = null;
		String ecname2 = null;
		
		for(byte v : str.getBytes())
			System.out.print(v+" "); //65 66 67 92 
		
		for(byte v : str.getBytes())
			System.out.print((char)v); // ABC\
		
		for(int i=0; i<str.length(); i++)
			System.out.print(str.charAt(i)); //ABC\

		ecname = new String(str.getBytes(), "utf-8");
		System.out.println(ecname);		// ABC\
		
		for(byte v : name.getBytes())
			System.out.print(v+" "); //-20 -96 -107 -20 -101 -112
			
		ecname2 = new String(name.getBytes(),"utf-8");
		System.out.println(ecname2); //정원
	}
}

 

- 2번째와 3번째 방식으로 동일한 결과를 얻을 수 있다. (사실 두 번째 코드가 이 페이지의 발단이었다. 앞으로 유용하게 사용할 듯하다.)

- 바이트 배열을 출력하면 1 바이트 단위로 표현되는 아스키코드 값으로 출력되는 것을 확인할 수 있다. 

- String 생성자를 통해 바이트 배열에 저장된(바이트 단위로 나눠진) 문자열을 다시 유니코드(2바이트 단위로 표현) 기반의 인코딩 방식으로 저장 및 출력 가능한 것을 확인할 수 있다. 

 

이외 도움받은 곳:

https://m.blog.naver.com/writer0713/220921933255

https://st-lab.tistory.com/63