Search code examples
javaarraysfileio

How can I read multiple grid from text file to 2D array in Java?


Here is the text file content:

5
3
*&*&*
&*&*&
*&*&*
50
5
*&&&&&&&&*&***************&**********************&
&&********&***************&&**********************
*&&**&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&*********&&***********&***************&*********
*&&&&&******&&*********&&&**************&********&

Here is my code currently:

public class Main {

    public static char[][] grid1 = new char[5][50];

    public static void readGridData (String fileName, char[][] grid) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        int columnCount = Integer.parseInt(br.readLine());
        int rowCount = Integer.parseInt(br.readLine());
        System.out.println(columnCount);
        System.out.println(rowCount);
        for (int i = 0; i < rowCount; i++) {
            String line = br.readLine();
            for (int j = 0; j < columnCount; j++) {
                grid[i][j] = line.charAt(j);
            }
        }
        br.close();
    }

    /* prints the 2D array given as argument */
    public static void printGrid(char[][] grid) {
        int rowLength = grid.length;
        int columnLength = grid[0].length;
        for (int i = 0; i < rowLength; i++) {
            for (int j = 0; j < columnLength; j++) {
                System.out.print(grid[i][j]);
            }
            System.out.println();
        }
        System.out.println();
    } // End of printGrid

    public static void main(String args[]) throws IOException {
        readGridData("simple.txt", grid1);
        printGrid(grid1);
    }

}

The output is only the first grid, which is 5, 3, and the grid itself. How can I continue to read the whole text file?

Later I will count blob with the array so is there any best way to optimize this?

I cannot use ArrayList for this. Thank you very much for your help!


Solution

  • Declare and initialise your buffer outside of the readGridData method and then pass it a parameter. In that case you'll be able to continue reading.

    I'd even use a Scanner instead:

    public static char[][] readGridData(Scanner scanner) {
        int columnCount = scanner.nextInt();
        int rowCount = scanner.nextInt();
        System.out.println(columnCount);
        System.out.println(rowCount);
        char[][] grid = new char[rowCount][columnCount]
        for (int i = 0; i < rowCount; i++) {
            String line = scanner.nextLine();
            for (int j = 0; j < columnCount; j++) {
                grid[i][j] = line.charAt(j);
            }
        }
        return grid;
    }
    

    and then:

    public static void main(String args[]) throws IOException {
        try (Scanner scanner = new Scanner("simple.txt")) {
            while (scanner.hasNextInt()) {
                char[][] grid = readGridData(scanner);
                printGrid(grid);
            }
        }
    }