我想将字符串转换为具有相同内容的 byte[]。例我有:
String str = "abc";
byte[] bytes;
//I want to convert "str" to "bytes" that they have same content:
(code here)
//after, print bytes -> "abc".
只要稍加努力,你就会达到这个目标。
所以我们要做的是使用getBytes
方法
byte[] convertToBytes= stuff.getBytes("UTF-8");
String newString = new String(convertToBytes, "UTF-8");
源
将一组字符串转换为 byte[] 数组
还可以在字符串 API 页面上学习
String str = "abc";
byte bytes[] = str.getBytes(); // Get the byte array
for (byte b : bytes) {
System.out.println("Byte is "+b); //Iterate and print
}
str = new String(bytes); // Create String from byte array
System.out.println("String is "+str);