Java 字符串和字节数组之间的相互转换
将字符串转换为字节数组:
String str = "Hello, World!";
byte[] byteArray = str.getBytes();
将字节数组转换为字符串:
byte[] byteArray = {72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33};
String str = new String(byteArray);
注意:在使用字符串转字节数组和字节数组转字符串时,需要注意字符编码的问题。可以使用指定的字符编码来进行转换,例如:
String str = "你好,世界!";
byte[] byteArray = str.getBytes("UTF-8");
String str = new String(byteArray, "UTF-8");
原文地址: https://www.cveoy.top/t/topic/pUDc 著作权归作者所有。请勿转载和采集!