Home > Back-end >  Java reading a 2d array
Java reading a 2d array

Time:09-22

I was able to get the program to read a 2D array from a txt file, but with only setting the row and column length beforehand.

Is there any way to make it so It can read any .txt file without having to preset the column and row length?

here's my code :

public class GridReader {
private static final int ROW = 3;
private static final int COL = 3;

public static void main(String[] args) throws FileNotFoundException {

    File file = new File("C:\\Users\\sitar\\Desktop\\GridReader\\src\\2dArray.txt");
    FileInputStream fis = new FileInputStream(file);

        int[][] array = new int[ROW][COL];
        Scanner sc = new Scanner(file);
        while (sc.hasNextLine()) {
            for (int i = 0; i < array.length; i  ) {
                String[] line = sc.nextLine().trim().split(","   " ");
                for (int j = 0; j < line.length; j  ) {
                    array[i][j] = Integer.parseInt(line[j]);
                }
            }
        }
    System.out.println("output:"   Arrays.deepToString(array));
    }
}

and here are the input file's contents: img of txt files contents 3 rows and 3 columns

and the output:

output:[[1, 2, 3], [3, 4, 5], [5, 6, 7]]

I have been trying to figure it out a way to take the input of any txt file and transfer it into a 2D array, any input or help would be appreciated.

CodePudding user response:

Elaborating about @PM77-1 's comment:

package examples.stackoverflow.q73792328;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class GridReader {
  public static void main(String[] args) throws IOException {

    if (args.length < 1) {
      System.err.println("filename argument missing");
    }
    File file = new File(args[0]);
    try(FileInputStream fis = new FileInputStream(file)) {
      List<List<Integer>> array = new ArrayList<>();
      Scanner sc = new Scanner(file);
      while(sc.hasNextLine()) {
        String[] line = sc.nextLine().trim().split(", ");
        array.add(Arrays.stream(line).map(Integer::parseInt).toList());
      }
      System.out.println("output:"   array);
    }
  }
}

I added the input filename as the first parameter of the program and also a try-with-resources so the stream is closed on success or error.

You might be able to improve the code and get rid of the while-loop if you replace the scanner with a BufferedReader and use the lines() method to also stream the lines.

  • Related