How to read a 2d array from a file in java?


A 2d array is an array of one dimensional arrays to read the contents of a file to a 2d array –

  • Instantiate Scanner or other relevant class to read data from a file.
  •  Create an array to store the contents.
  • To copy contents, you need two loops one nested within the other. the outer loop is to traverse through the array of one dimensional arrays and, the inner loop is to traverse through the elements of a particular one dimensional array.
  • Create an outer loop starting from 0 up to the length of the array. Within this loop read each line trim and split it using nextLine(), trim(), and split() methods respectively.
  • Create the second loop starting from 0 up to the length of the line. Within this loop convert each element of the string array to integer and assign to the array created in the previous step.

Example

import java.io.BufferedReader;
import java.io.FileReader;

import java.util.Arrays;
import java.util.Scanner;

public class Reading2DArrayFromFile {
   public static void main(String args[]) throws Exception {
      Scanner sc = new Scanner(new BufferedReader(new FileReader("sample.txt")));
      int rows = 4;
      int columns = 4;
      int [][] myArray = new int[rows][columns];
      while(sc.hasNextLine()) {
         for (int i=0; i<myArray.length; i++) {
            String[] line = sc.nextLine().trim().split(" ");
            for (int j=0; j<line.length; j++) {
               myArray[i][j] = Integer.parseInt(line[j]);
            }
         }
      }
      System.out.println(Arrays.deepToString(myArray));
   }
}


Output

[[2, 2, 2, 2], [6, 6, 6, 6], [2, 2, 2, 2], [4, 4, 4, 4]]

Updated on: 19-Feb-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements