如何将字符串转换为具有相同内容的byte []

时间:2014-02-27 17:41:42

标签: java string

我想将字符串转换为具有相同内容的byte []。例 我有:

String str = "abc";
byte[] bytes;
//I want to convert "str" to "bytes" that they have same content:
(code here)
//after, print bytes -> "abc".

2 个答案:

答案 0 :(得分:4)

只要付出一点努力,你就可以达到这一目标。

我们所做的就是使用getBytes方法

byte[] convertToBytes= stuff.getBytes("UTF-8");
String newString = new String(convertToBytes, "UTF-8");

source

Converting a set of strings to a byte[] array

Also study up on the String API page

答案 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);