如何在文本文件中保存矩阵

时间:2019-05-13 22:11:32

标签: java arrays file input io

我只想在文本文件中输入矩阵,但是结果明显不同。我没有任何想法。

public void saveToTextFile() {
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(new File("matrix.txt")));

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                writer.write(matrix[i][j] + " ");
            }
            writer.newLine();
        }
        writer.flush();
        writer.close();

    } catch (IOException e) {
        System.out.println("Error");
    }
}

我希望

1 2 3
4 5 6
7 8 9

但在文件中是

1 1 1
5 5 5
9 9 9

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

int[][] ints = new int[4][4]; // Let's say you have a 4 * 4 ints array filled like this

        ints[0][0] = 1;
        ints[0][1] = 2;
        ints[0][2] = 3;
        ints[0][3] = 4;

        ints[1][0] = 5;
        ints[1][1] = 6;
        ints[1][2] = 7;
        ints[1][3] = 8;

        ints[2][0] = 9;
        ints[2][1] = 10;
        ints[2][2] = 11;
        ints[2][3] = 12;

        ints[3][0] = 13;
        ints[3][1] = 14;
        ints[3][2] = 15;
        ints[3][3] = 16;

        StringBuilder sb = new StringBuilder(); // String Builder to create the table structure before writing it to the file.

        for (int[] int1 : ints) {
            for (int j = 0; j < int1.length; j++) {
                sb.append(int1[j]).append("\t"); // Add tab to delimite the elements
            }
            sb.append("\r\n"); // Add new line character
        }

        System.out.println(sb);

        Path path = Paths.get("C:\\Users\\youruser\\Documents\\test.txt"); // The path to your file

        Files.write(path, sb.toString().getBytes()); // Writes to that path the bytes in the string from the stringBuilder object.

这将像表格一样打印值:

enter image description here

答案 1 :(得分:0)

对您的方法稍作修改:

try {
            int[][] matrix = new int[3][3];
            BufferedWriter writer = new BufferedWriter(new FileWriter(new File("matrix.txt")));

            int num = 1;

            for (int i = 0; i < matrix.length; i++) {
                for (int j = 0; j < matrix[i].length; j++) {
                    writer.write(num + " ");
                    num++;
                }

                writer.newLine();
            }
            writer.flush();
            writer.close();

        } catch (Exception e) {
            System.out.println("Error");
        }