java二维数组怎么存入io中

Java 二维数组存储到 IO 中需要以下步骤:1. 使用 ObjectOutputStream 序列化数组;2. 使用 ObjectInputStream 反序列化数组;3. 使用 PrintStream 将数组写入文本文件(空格分隔);4. 使用 BufferedWriter 将数组写入文本文件(逗号分隔)。

如何将 Java 二维数组存储到 IO 中

将 Java 二维数组存储到输入/输出 (IO) 中的过程涉及以下步骤:

1. 序列化数组

使用 ObjectOutputStream 类将二维数组序列化为字节流。

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("array.dat"));
oos.writeObject(array);
oos.close();

2. 反序列化数组

使用 ObjectInputStream 类将序列化的字节流反序列化为二维数组。

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(

"array.dat")); int[][] array = (int[][]) ois.readObject(); ois.close();

3. 使用 PrintStream 写入数组到文件中

使用 PrintStream 类将二维数组写入文本文件中,每个元素以空格分隔。

try (PrintStream ps = new PrintStream("array.txt")) {
    for (int[] row : array) {
        for (int element : row) {
            ps.print(element + " ");
        }
        ps.println();
    }
} catch (IOException e) {
    e.printStackTrace();
}

4. 使用 BufferedWriter 写入数组到文件中

使用 BufferedWriter 类将二维数组写入文本文件中,每个元素以逗号分隔。

try (BufferedWriter bw = new BufferedWriter(new FileWriter("array.csv"))) {
    for (int[] row : array) {
        for (int element : row) {
            bw.write(element + ",");
        }
        bw.newLine();
    }
} catch (IOException e) {
    e.printStackTrace();
}