📄 二维数组的存储问题.txt
字号:
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();
}
}
另外的一种方法:
首先,使用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();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -