【发布时间】:2014-02-23 08:43:45
【问题描述】:
我想将一些整数和一些字符串转换为单字节数组,然后再转换回来。我已经对如何进行转换进行了一些研究,但我不确定它是否都正确。
将字符串转换为字节数组很简单:byte[] bytes = string.getBytes();
通过Arrays.toString() 再次将其转换回来,因为这只会创建一个字节字符串。
这行得通吗:String s = new String(bytes);?
将整数转换为字节数组是这样的:
int[] data = { int1, int2, int3 };
ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(data);
byte[] my_app_state = byteBuffer.array();
但我不知道如何再次将其转换回来。
我的目标是将 4 个整数和 2 个字符串转换为 单 字节数组,然后再将它们转换回来。
例如。我有这些对象,并希望将它们转换为相同的字节数组。
int int1 = 1;
int int2 = 2;
int int3 = 3;
int int4 = 4;
String s1 = "mystring1"
String s2 = "mystring2"
更新:删除了我认为有问题的代码。没有。
【问题讨论】:
-
如果你捕捉到一个异常,打印它并假装它没有发生是没有意义的。如果你不捕获 IOException,你的代码会更简单,除非你知道如何处理它。
标签: java arrays string int byte