2D数组到int(种子)和返回

时间:2016-03-10 17:43:41

标签: java arrays serialization libgdx server

我有一个问题......

这里有一个2d字节的数组:

byte [] [] duengonMap = new byte [500] [500];

因为我想将它从客户端发送到服务器或 反过来说,我需要将它放入int / long。从服务器将它发送到其他连接的客户端,它将转换回二维数组。这听起来很简单......但我该怎么做?

我尝试过类似的东西:

int[][] twoD = new int[][] { new int[] { 1, 2 },
        new int[] { 3, 4 } };

int[][] newTwoD = null; // will deserialize to this

System.out.println("Before serialization");
for (int[] arr : twoD) {
    for (int val : arr) {
        System.out.println(val);
    }
}

try {
    FileOutputStream fos = new FileOutputStream("test.dat");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(twoD);

    FileInputStream fis = new FileInputStream("test.dat");
    ObjectInputStream iis = new ObjectInputStream(fis);
    newTwoD = (int[][]) iis.readObject();

} catch (Exception e) {

}

System.out.println("After serialization");
for (int[] arr : newTwoD) {
    for (int val : arr) {
        System.out.println(val);
    }
}
}

它只被转换成“文件”,也许我做错了, 但我不知道如何将其转换为int或long ... 有任何想法吗 ?还是例子?

2 个答案:

答案 0 :(得分:0)

您可以使用循环逐个发送所有值,并在服务器/客户端上同时读取它们并将它们排列回数组

答案 1 :(得分:0)

基本上,有两个问题需要解决。

1)如何将一个字节转换为一个int,反之亦然......这是非常直接的,并且已经在这里回答了无数次。 见here fore example

2)现在,您知道如何发送一个byte / int ...您唯一需要做的就是定义一个您想要遍历数组的顺序。含义:遍历字节数组,将每个字节作为int发送;另一方面,您读取int值,并使用相同的遍历算法填充您的字节数组。

当然,最简单的解决方案是嵌套for循环;但取决于你的数据;您可能会发现其他有用的想法。例如:如果你的字节数组包含许多0值...你可能决定只传输非0值(比如发送一个由index +值组成的对)。