Java
Java - byte[]를 String으로 변환
codeManager
2022. 7. 15. 18:10
반응형
자바에서 String을 byte[] 로 변환하여 파일에 저장하거나,
데이터로부터 byte[]를 읽어와서 String으로 변환할 수 있습니다.
1. String to byte[], byte[] to String
class BytesToString {
public static void main(String[] args) {
String str = "string to bytes\n";
byte[] bytes = str.getBytes();
System.out.println("str: " + str);
String bytesToStr = new String(bytes);
System.out.println("bytes to str: " + bytesToStr);
}
}
str.getBytes()를 이용해서 byte[]로 변환합니다.
new String(byte[])를 이용해서 byte[]를 String으로 바꿀 수 있습니다.
결과
str: string to bytes
bytes to str: string to bytes
2. byte[] to String 시 Character encoding
import java.nio.charset.StandardCharsets;
class BytesToString {
public static void main(String[] args) {
String str = "string to bytes";
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
System.out.println("str: " + str);
String convertedStr = new String(bytes, StandardCharsets.UTF_8);
System.out.println("converted str: " + convertedStr);
}
}
byte[]로 변환 시 charsets을 설정해서 변환할 수 있습니다.
결과
str: string to bytes
converted str: string to bytes
반응형