日期:2014-05-20  浏览次数:20838 次

J2ME中二维整型数组的存储问题!
一个基本的8*8二维int型数组data[][],怎样的存储到RMS中,并读出的时候转化为二维数组?
String s= new string(""+data);
/数据库操作
writeUTF(s);
再读数据库时
String s1=readUTF();

可运行到
data1=Integer.parseInt(new String(s1));的时候,发现data1为NULL!
难道我的这种方法不对,只能存储一维数组?有没遇到过类似问题的指点个方法!

------解决方案--------------------
首先,使用ByteArrayOutputStream将整型数组转换成字节流。
然后,将字节流以byte数组的形式当做一条记录存入到RMS中。

读取的时候,先从RMS中取出该字节数组。
然后使用ByteArrayInputStream将该字节数组还原为整型数组。

切忌,不要直接一个一个的向RMS里插入整型数据,然后一个一个读出来。这样的操作非常业余。
以下是部分实现代码,手边没有编辑器,只写了关键部分,你凑合看。

//生成测试数据
int[][] test = new int[8][8];
for (int i = 0; i < test.length; i++) {
for (int j = 0; j < test[i].length; j++) {
test[i][j] = 123;
}
}

//将测试数据转换为byte数组
byte[] data = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
for (int i = 0; i < test.length; i++) {
for (int j = 0; j < test[i].length; j++) {
dos.writeInt(test[i][j]);
}
}
data = baos.toByteArray();
dos.close();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
//此时可以直接将data存入RMS,具体代码省略


//读取时使用如下方法,需要先从RMS里取出byte数组data,然后用data构造ByteArrayInputStream
int[][] result = new int[8][8];
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
DataInputStream dis = new DataInputStream(bais);
for (int i = 0; i < test.length; i++) {
for (int j = 0; j < result[i].length; j++) {
result[i][j] = dis.readInt();
}
}
} catch (Exception e) {
e.printStackTrace();
}


其实上面的两个操作,将数据转换为byte流,以及将byte流再转换回数据;经常在对一个对象进行序列化的时候使用。
这里你可以修改转换和读取的代码,将数组长度等信息事先写到byte流中。这样就可以在读取时根据“头信息”自动创建合适的数组。
其余的你尝试一下吧。


------解决方案--------------------
1.转成一维数组来存储
2.如果你非要写成二维数组来存储的话, 可以这样
Java code

//写入RMS
int[][] arr;
int rows = arr.length;
dos.writeInt(rows);
for(int i = 0; i < arr.length; i++) {
    int cols = arr[i].length;
    dos.writeInt(cols);
    for(int j = 0; j < cols; j++) {
        dos.writeInt(arr[i][j]);
    }
}

//读的时候这样读
int[][] arr = null;
int rows = dis.readInt();
arr = new int[rows][];
for(int i = 0; i < rows; i++) {
    int cols = dis.readInt();
    arr[i] = new int[cols];
    for(int j = 0; j < cols; j++) {
        arr[i][j] = dis.readInt();
    }
}

------解决方案--------------------
用分隔符吧,比如temp={{1,1}{2,2}}可以为String str="1,1|2,2"然后保存进RMS,取的时候再分割提取,,,J2SE里的split方法移植到ME里就OK了。