如何将文件读入2D数组

时间:2013-01-23 19:26:41

标签: java arrays bufferedreader

下午好,

我目前正致力于以

的格式阅读文件
5 5
0     0     0     0     0
0     0     0     0     0
0     0     0     0     0
0     0     0     0     0
0     0     0     0     0

进入2D数组。

第一行是2D数组的行长度和列长度(即5x5)。

前进行被赋予输入值(值本身并不重要,只有它们是整数),需要将其读入2D数组,使得数组[0] [0] = 0,数组[0] [1] = 0等。

我目前正在吮吸的是,在第一行之后读取文件的内容并显示它到目前为止是什么,

public static void importFile(String fileName) throws IOException 
{
    int rows = 0;
    int cols = 0;

    int[][] numArray = null;

    try {
        int count = 0;

        BufferedReader reader = new BufferedReader(new FileReader(fileName));

        String line;
        while ((line = reader.readLine()) != null) 
        {
           count++;

            if (count == 1) 
            {
                String[] tokenizer = line.split("\\s+");

                rows = Integer.parseInt(tokenizer[0]);
                System.out.println(rows);

                cols = Integer.parseInt(tokenizer[1]);
                System.out.println(cols);

                numArray = new int[rows][cols];

            } // end of if statement
            else if(count > 1)
            {
                String[] tokenizer = line.split("   ");

                    for(int j = 0; j < tokenizer.length; j++)
                    {
                        numArray[rows][j] = Integer.parseInt(tokenizer[j]);
                        System.out.print(numArray[rows][j] + " ");
                    }
                    System.out.println("");

                rows++;

            } // end of else if

        }// end of while loop

    } //end of try statement
    catch (Exception ex) {
        System.out.println("The code throws an exception");
        System.out.println(ex.getMessage());
    } 

    System.out.println("I am printing the matrix: ");
    for (int i = 0; i < rows; i++) {
        for(int j=0; j < cols; j++)
            System.out.print(numArray[i][j] + " ");
        System.out.println("");
    }  
} // end of import file

} //课程结束 输出是给定的

Please enter the file you'd like to use: 
data4.txt
5
5
The code throws an exception
5
I am printing the matrix: 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 

1 个答案:

答案 0 :(得分:0)

我在另一个答案下进行了扩展讨论。由于您的代码显示您尝试过(并且非常接近),因此我将为您的问题发布一个强大的解决方案。我完全重写了它,因为你的程序有很多小错误,而且要详细说明每一个错误都需要做更多工作。以下方法将读取指定格式的文件并返回结果int[][]。如果您的文件中有错误,该方法将告诉您;)

public static int[][] importFile(String fileName) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    int[][] numArray;
    String line = reader.readLine();
    if (line == null) {
        throw new IllegalArgumentException("There was no 1st line.");
    }
    String[] dimensions = line.split("\\s+");
    try {
        int rows = Integer.parseInt(dimensions[0]);
        int cols = Integer.parseInt(dimensions[1]);
        // TODO: check for negative values.
        numArray = new int[rows][cols];
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("First line of file has to be 'rows cols'");
    }

    int row = 0; 

    while ((line = reader.readLine()) != null && row < numArray.length) {
        String[] tokens = line.split("\\s+");
        if (tokens.length > numArray[row].length) {
            throw new IllegalArgumentException("Too many values provided in matrix row " + row);
        }
        // to less values will be filled with 0. If you don't want that
        // you have to uncomment the next 3 lines.
        //if (tokens.length < numArray[row].length) {
        //  throw new IllegalArgumentException("Not enough values provided in matrix row " + row);
        //}
        for(int column = 0; column < tokens.length; column++) {
            try {
                int value = Integer.parseInt(tokens[column]);
                numArray[row][column] = value; 
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Non numeric value found in matrix row " + row + ", column " + column);
            }
        }
        row++;
    }
    if (line != null) {
        // there were too many rows provided.
        // Superflous ones are ignored.
        // You can also throw exception, if you want.
    }
    if (row < numArray.length) {
        // There were too less rows in the file. If that's OK, the
        // missing rows will be interpreted as all 0.
        // If that's OK with you, you can comment out this whole
        // if block
        throw new IllegalArgumentException("Expected " + numArray.length + " rows, there only were " + row);
    }
    try {
        reader.close(); // never forget to close a stream.
    } catch (IOException e) { }
    return numArray;
}