13

我有一个要转换为一维字节数组的一维字符串数组。我该怎么做呢?这需要 ByteBuffer 吗?我怎样才能做到这一点?(字符串可以是任意长度,只是想知道如何进行这样的操作。在将其转换为字节数组之后,我如何将其转换回字符串数组?

-担

4

7 回答 7

14

数组到数组,您应该手动将其解析为双方,但如果您只有一个字符串,您可以String.getBytes()new String(byte[] data); 像这样

public static void main(String[] args) {
    String[] strings = new String[]{"first", "second"};
    System.out.println(Arrays.toString(strings));
    byte[][] byteStrings = convertToBytes(strings);
    strings = convertToStrings(byteStrings);
    System.out.println(Arrays.toString(strings));

}

private static String[] convertToStrings(byte[][] byteStrings) {
    String[] data = new String[byteStrings.length];
    for (int i = 0; i < byteStrings.length; i++) {
        data[i] = new String(byteStrings[i], Charset.defaultCharset());

    }
    return data;
}


private static byte[][] convertToBytes(String[] strings) {
    byte[][] data = new byte[strings.length][];
    for (int i = 0; i < strings.length; i++) {
        String string = strings[i];
        data[i] = string.getBytes(Charset.defaultCharset()); // you can chose charset
    }
    return data;
}

对于 string[] 中的一个字节[],您必须:

  • 使用一些分隔符从每个字符串到 byteArray 连接字节数组
  • 从 bytearray 按相同的分隔符拆分并创建字符串,如上所述。
于 2013-02-03T05:43:06.683 回答
4

您没有说要对字节做什么(除了将它们转换回String[]之后),而是假设您可以将它们视为不透明的数据包(因此您可以将它们保存到文件中或将它们发送过来网络之类的,但你不需要以任何方式检查或修改它们),我认为你最好的选择是使用序列化。要序列化您的字符串数组,您可以编写如下内容:

final String[] stringArray = { "foo", "bar", "baz" };

final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final ObjectOutputStream objectOutputStream =
    new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(stringArray);
objectOutputStream.flush();
objectOutputStream.close();

final byte[] byteArray = byteArrayOutputStream.toByteArray();

并在之后恢复它,你会写相反的:

final ByteArrayInputStream byteArrayInputStream =
    new ByteArrayInputStream(byteArray);
final ObjectInputStream objectInputStream =
    new ObjectInputStream(byteArrayInputStream);

final String[] stringArray2 = (String[]) objectInputStream.readObject();

objectInputStream.close();
于 2013-02-03T06:04:10.020 回答
1

你可以检查这个

package javaapplication2;

import java.util.Arrays;


/**
 *
 * @author Ali
 */
public class JavaApplication2 {


 public static byte[] to_byte(String[] strs) {
        byte[] bytes=new byte[strs.length];
        for (int i=0; i<strs.length; i++) {
            bytes[i]=Byte.parseByte(strs[i]);
        }
        return bytes;
    }


    public static void main(String[] args) {
        String[] input = {"1","2","3"};       //original data
        byte[] byteArray = to_byte(input);//data to byte array
        String[] recovered=Arrays.toString( byteArray).split(",");// recovered data 

    }    
}
于 2014-10-31T20:36:06.133 回答
1

首先像我在这里声明的那样声明字符串str="Suresh"
第二次使用getBytes()以字节为单位将其转换
getBytes返回字节数组。

String str="Suresh";
byte[] s=str.getBytes();
于 2015-07-31T16:13:20.953 回答
0

我会将其视为序列化问题,并按如下方式实现(完整且有效的 Java 代码):

import java.nio.ByteBuffer;
import java.util.ArrayList;

public class Serialization {
    public static byte[] serialize(String[] strs) {
        ArrayList<Byte> byteList = new ArrayList<Byte>();
        for (String str: strs) {
            int len = str.getBytes().length;
            ByteBuffer bb = ByteBuffer.allocate(4);
            bb.putInt(len);
            byte[] lenArray = bb.array();
            for (byte b: lenArray) {
                byteList.add(b);
            }
            byte[] strArray = str.getBytes();
            for (byte b: strArray) {
                byteList.add(b);
            }
        }
        byte[] result = new byte[byteList.size()];
        for (int i=0; i<byteList.size(); i++) {
            result[i] = byteList.get(i);
        }
        return result;
    }

    public static String[] unserialize(byte[] bytes) {
        ArrayList<String> strList = new ArrayList<String>();
        for (int i=0; i< bytes.length;) {
            byte[] lenArray = new byte[4];
            for (int j=i; j<i+4; j++) {
                lenArray[j-i] = bytes[j];
            }
            ByteBuffer wrapped = ByteBuffer.wrap(lenArray);
            int len = wrapped.getInt();
            byte[] strArray = new byte[len];
            for (int k=i+4; k<i+4+len; k++) {
                strArray[k-i-4] = bytes[k];
            }
            strList.add(new String(strArray));
            i += 4+len;
        }
        return strList.toArray(new String[strList.size()]);
    }

    public static void main(String[] args) {
        String[] input = {"This is","a serialization problem;","string concatenation will do as well","in some cases."};
        byte[] byteArray = serialize(input);
        String[] output = unserialize(byteArray);
        for (String str: output) {
            System.out.println(str);
        }
    }
}

这个想法是,在生成的字节数组中,我们存储第一个字符串的长度(如果我们使用 type ,则始终为 4 个字节int),然后是第一个字符串的字节(稍后可以从前面的 4 个字节中读取其长度) ),然后是第二个字符串的长度和第二个字符串的字节数,以此类推。这样,字符串数组可以很容易地从生成的字节数组中恢复,如上面的代码所示。而且这种序列化方法可以处理任何情况。

如果我们对输入字符串数组做一个假设,代码会简单得多:

public class Concatenation {
    public static byte[] concatenate(String[] strs) {
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<strs.length; i++) {
            sb.append(strs[i]);
            if (i != strs.length-1) {
                sb.append("*.*"); //concatenate by this splitter
            }
        }
        return sb.toString().getBytes();
    }

    public static String[] split(byte[] bytes) {
        String entire = new String(bytes);
        return entire.split("\\*\\.\\*");
    }

    public static void main(String[] args) {
        String[] input = {"This is","a serialization problem;","string concatenation will do as well","in some cases."};
        byte[] byteArray = concatenate(input);
        String[] output = split(byteArray);
        for (String str: output) {
            System.out.println(str);
        }
    }
}

假设是*.*输入数组中的任何字符串都不存在。换句话说,如果您事先知道某些特殊的符号序列不会出现在输入数组的任何字符串中,您可以使用该序列作为拆分器。

于 2013-02-03T06:33:57.093 回答
0

String.getBytes()? 就是你要找的。

于 2013-02-03T05:42:01.870 回答
0

您可以迭代每个字符串并继续附加到最终的字节数组。

String example = "This is an example";
//Convert String to byte[] using .getBytes() function
byte[] bytes = example.getBytes();
//Convert byte[] to String using new String(byte[])      
String s = new String(bytes);
于 2013-02-03T05:43:09.580 回答