如何将字符串数组转换为字节数组?(爪哇) [英] How to convert a String array to a Byte array? (java)
问题描述
我有一个一维字符串数组,我想将其转换为一维字节数组.我该怎么做呢?这需要 ByteBuffer 吗?我怎样才能做到这一点?(字符串可以是任意长度,只是想知道如何进行这样的操作.将其转换为字节数组后,如何将其转换回字符串数组?
I have a one dimensional String array that I want to convert into a one dimensional byte array. How do I do this? Does this require ByteBuffer? How can I do this? (The strings can be any length, just want to know how to go about doing such an act. And after you convert it into a byte array how could I convert it back into a String array?
-丹
推荐答案
Array to Array 你应该手动转换成两边,但如果你只有一个String 你可以 String.getBytes()
和 new String(byte[] data)
;像这样
Array to Array you should convert manually with parsing into both sides, but if you have just a String you can String.getBytes()
and new String(byte[] data)
;
like this
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[] 中的一个 byte[],您必须:
for one byte[] from string[] you have to:
- to byteArray 使用一些分隔符从每个字符串连接字节数组
- from bytearray 由 te 相同的分隔符分割并创建 String as I如上所述.
这篇关于如何将字符串数组转换为字节数组?(爪哇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!