我想将字符串转换为具有相同内容的byte []。例 我有:
String str = "abc";
byte[] bytes;
//I want to convert "str" to "bytes" that they have same content:
(code here)
//after, print bytes -> "abc".
答案 0 :(得分:4)
只要付出一点努力,你就可以达到这一目标。
我们所做的就是使用getBytes
方法
byte[] convertToBytes= stuff.getBytes("UTF-8");
String newString = new String(convertToBytes, "UTF-8");
答案 1 :(得分:1)
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);