java 将string转换成byte_如何将String数组转换为Byte数组? (Java)的

我会将此视为序列化问题,并将其实现如下(完整且可用的Java代码):

import java.nio.ByteBuffer;

import java.util.ArrayList;

public class Serialization {

public static byte[] serialize(String[] strs) {

ArrayList byteList = new ArrayList();

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

result[i] = byteList.get(i);

}

return result;

}

public static String[] unserialize(byte[] bytes) {

ArrayList strList = new ArrayList();

for (int i=0; i< bytes.length;) {

byte[] lenArray = new byte[4];

for (int j=i; 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

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

}

}

}我们的想法是,在生成的字节数组中,我们存储第一个字符串的长度(如果我们使用int类型,则总是4个字节),然后是第一个字符串的字节(其长度可以在后面的4个字符串中读取)字节),然后是第二个字符串的长度和第二个字符串的字节,依此类推。这样,可以从生成的字节数组中轻松恢复字符串数组,如上面的代码所示。这种序列化方法可以处理任何情况。

如果我们对输入字符串数组做出假设,代码可以更简单:

public class Concatenation {

public static byte[] concatenate(String[] strs) {

StringBuilder sb = new StringBuilder();

for (int i=0; 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);

}

}

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值