1

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.

4
  • 1
    Use ArrayList instead for both rows and columns. Commented Sep 20, 2022 at 20:35
  • would you be able to elaborate more? Commented Sep 20, 2022 at 20:41
  • You have two options here. The first: is to use List instead of Array. With this approach you don't need to set the size of your matrix. You don't need for (int i = 0; i < array.length; i++) each sc.nextLine() will give you the next row. Second: is to read all your file first and find your ROW value. Commented Sep 20, 2022 at 20:45
  • Lets start simple. If your file would contain only 1D array, so only one line like 1, 2, 3, 4 would you be able to convert it to double[]? When you solve this step you are almost there. Next information you need is amount of rows which you can obtain by reading your file once to count its lines which also represents amount of rows. Then you just need to iterate your file second time, convert each line to 1D array, and place that array in 2D array. Commented Sep 20, 2022 at 20:46

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.