[JAVA] Byte to String / String to Byte

[JAVA] Byte to String / String to Byte

* Byte to String

String result = new String(bytes);

또는

String result = new String(bytes, Charset.forName(charset));

ex 1) String result = new String(bytes, Charset.forName(“UTF-8”));

ex 2) String result = new String(bytes, Charset.forName(“EUC-KR”));

* String to Byte

byte[] bytes = str.getBytes();

또는

byte[] bytes = str.getBytes(charset);

ex 1) byte[] bytes = str.getBytes(“UTF-8”);

ex 2) byte[] bytes = str.getBytes(“EUC-KR”);

———-

2020. 02. 27(목) 내용 추가.

위 내용처럼 Byte to String 을 수행해도 되지만, 스트링이 깨져나오는 현상이 있었다.

byte[] 배열의 내용을 for문을 이용해서 찍어보니 마이너스 값이 많이 찍혀나왔다.

특히 String 을 다시 byte 로 되돌려도 문자열이 정상적으로 복원되지 않았다.

이런 경우 Base64 를 이용해서 Byte to String 과 String to Byte 를 수행하면 문자열이 깨지지 않고 변환되었다.

* Byte to String

String result = Base64.encodeBase64URLSafeString(bytes);

* String to Byte

byte[] bytes = Base64.decodeBase64(str);

Base64 는 아래 패키지를 임포트하면 사용할 수 있다.

import org.apache.commons.codec.binary.Base64;