Java 从文件中读取二维数组

标签 java file file-io

假设我有一个以下格式的文件:

3
4
1,2,3,4
5,6,7,8
9,10,11,12

文件的前两行表示二维数组的行数和列数。此后,每一行代表二维数组每一行的值。我正在尝试读取此文件并在 java 中创建一个二维整数数组。我尝试了以下代码:

public class PrintSpiral {
    private static BufferedReader in = null;
    private static int rows = 0;
    private static int columns = 0;
    private static int [][] matrix = null;
    public static void main(String []args) throws Exception {
        try {
            String filepath = args[0];
            int lineNum = 0;

            int row=0;
            in = new BufferedReader(new FileReader(filepath));
            String line = in.readLine();
            while(line!=null) {
                lineNum++;
                if(lineNum==1) {
                    rows = Integer.parseInt(line);
                    System.out.println("The number of rows of the matrix are: " + rows);
                } else if(lineNum==2) {
                    columns = Integer.parseInt(line);
                    System.out.println("The number of columns of the matrix are: " + columns);
                    matrix = new int[rows][columns];
                } else {
                    String [] tokens = line.split(",");
                    for (int j=0; j<tokens.length; j++) {
                        System.out.println("I am filling the row: " + row);
                        matrix[row][j] = Integer.parseInt(tokens[j]);
                    }
                    row++;
                }
            }
        } catch (Exception ex) {
            System.out.println("The code throws an exception");
            System.out.println(ex.getMessage());
        } finally {
            if (in!=null) in.close();
        }
        System.out.println("I am printing the matrix: ");
        for (int i=0; i < rows; i++) {
            for(int j=0; j < columns; j++)
                System.out.print(matrix[i][j]);
            System.out.println("");
        }
    }
}

我看到的输出是:

The number of rows of the matrix are: 3
The number of columns of the matrix are: 3
I am filling the row: 0
I am filling the row: 1
I am filling the row: 2
I am filling the row: 3
The code throws an exception
3
I am printing the matrix: 
300
300
300
3 0 0 0 0 0 3 3 0

很明显,java 代码没有正确读取文件。另外,我的代码抛出异常。我不确定是什么原因导致此异常。我似乎无法弄清楚我的代码有什么问题。谢谢!

最佳答案

改变

in = new BufferedReader(new FileReader(filepath));
String line = in.readLine();
while(line!=null) { .....

in = new BufferedReader(new FileReader(filepath));
String line = null;
while((line = in.readLine()) !=null) { .....

在每个循环开始时读取一个新行

关于Java 从文件中读取二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7797284/

相关文章:

java - 监听多个目录以在 Java 中创建文件

c - 尝试根据排序的学生 ID 显示文件中的学生数据

c - C 语言中可以并行执行输入/输出操作吗?

c++ - 用C++解析文件并将其写入表格中的HTML

java - 当我设置此按钮的可见性消失时出现了一个 SCSS

java - 在java中移动大文件

java - java.util.HashMap 的 Intellij 弃用警告

java - Java中获取文件所在驱动器的最佳方法是什么?

java - 在 Android 设备上将视频转换为音频 (Java)

java - 如何按升序和降序对带分隔符的字符串列表进行排序