如何将字符串转换为字节数组?

时间:2013-09-12 07:15:59

标签: java

假设我有两个String喜欢

txt1="something 1";
txt2="something 2";

现在想要从byte[] str= new byte[]; s

创建String
byte[] t1,t2;
t1=txt1.getBytes();
t2=txt2.getBytes();
byte[] strings = { t1,t2};

5 个答案:

答案 0 :(得分:5)

首先,我建议使用getBytes()而不先指定编码。 (我通常更喜欢UTF-8,但这取决于你想要的东西。)

其次,如果你只想要一个字符串的字节后跟另一个字节的字节,最简单的方法是使用字符串连接:

byte[] data = (txt1 + txt2).getBytes(StandardCharsets.UTF_8);

或者你可以分别获取每个字节数组,然后通过创建一个足够大的新字节数组来组合它们,并复制数据:

byte[] t1 = txt1.getBytes(StandardCharsets.UTF_8);
byte[] t2 = txt2.getBytes(StandardCharsets.UTF_8);
byte[] both = new byte[t1.length + t2.length];
System.arraycopy(t1, 0, both, 0, t1.length);
System.arraycopy(t2, 0, both, t1.length, t2.length);

我自己使用字符串连接版本:)

答案 1 :(得分:5)

最简单的方法是:

byte[] strings = (t1+t2).getBytes();

否则,您必须手动分配足够大的数组并复制单个字节。我很确定标准API中没有数组连接实用程序功能,尽管Apache Commons中可能还有一个...

哦,是的,通常你想在使用getBytes()时指定编码,而不是依赖平台默认编码。

答案 2 :(得分:1)

因为txt1.getBytes()返回byte[]。您正尝试在数组中分配多个byte[]。将数组和赋值合并到其中。

byte[] combined = new byte[array1.length + array2.length];

答案 3 :(得分:1)

您必须分配新的字节数组并将两个字节数组的内容复制到新的字节数组中:

byte[] t1 = txt1.getBytes();
byte[] t2 = txt2.getBytes();

byte[] result = new byte[t1.length + t2.length];

System.arraycopy(t1, 0, result, 0, t1.length);
System.arraycopy(t2, 0, result, t1.length, t2.length);

答案 4 :(得分:1)

最简单的方法是使用字符串连接并转换为字节数组。

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String txt1="something 1",txt2="something 2";
        //Use '+' string concatenation and convert into byte array.
        byte[] data = (txt1 + txt2).getBytes();
        System.out.println(data);
    }
}