- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]]
- Related Articles
- How to read the data from a file in Java?
- How to store a 2d Array in another 2d Array in java?
- How to read integers from a file using BufferedReader in Java?
- How to read data in from a file to String using java?
- How to read certain number of elements from a file in Java?
- How to read the data from a properties file in Java?\n
- How to read the data from a CSV file in Java?\n
- How to read data from .csv file in Java?
- How to create a dynamic 2D array in Java?
- how to shuffle a 2D array in java correctly?
- How to populate a 2d array with random alphabetic values from a range in Java?
- How to read/write data from/to .properties file in Java?
- How to read a Specific Line From a File in Linux?
- How to read a .txt file with RandomAccessFile in Java?
- How to read data from one file and print to another file in Java?

Advertisements