Java Read Text File Into 2d Array of Strings
How to read a 2nd array from a file in coffee?
A 2d array is an array of 1 dimensional arrays to read the contents of a file to a second array –
- Instantiate Scanner or other relevant class to read data from a file.
- Create an array to store the contents.
- To copy contents, you demand 2 loops one nested inside the other. the outer loop is to traverse through the assortment of one dimensional arrays and, the inner loop is to traverse through the elements of a item 1 dimensional assortment.
- Create an outer loop starting from 0 up to the length of the array. Inside this loop read each line trim and dissever information technology using nextLine(), trim(), and split() methods respectively.
- Create the second loop starting from 0 up to the length of the line. Inside this loop catechumen each chemical element of the string array to integer and assign to the assortment created in the previous step.
Instance
import java.io.BufferedReader; import java.io.FileReader; import java.util.Arrays; import java.util.Scanner; public grade Reading2DArrayFromFile { public static void chief(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]); } } } Arrangement.out.println(Arrays.deepToString(myArray)); } }
Output
[[2, two, ii, 2], [six, half dozen, vi, 6], [two, 2, two, 2], [four, 4, iv, 4]]
Published on 09-Jan-2018 09:32:37
- Related Questions & Answers
- How can we store / write and read 2nd array from file in C#?
- How to read the information from a file in Coffee?
- How to read the data from a properties file in Java?
- How to read the information from a CSV file in Java?
- How to read integers from a file using BufferedReader in Coffee?
- How to store a 2d Assortment in another second Array in java?
- How to read information in from a file to Cord using java?
- How to read certain number of elements from a file in Coffee?
- How to read data from a file using FileInputStream?
- How to read a file from assets on android?
- How to read information from .csv file in Java?
- How to read a text file from resources in Kotlin?
- How to create a dynamic 2D array in Java?
- how to shuffle a 2d array in java correctly?
- How to read a file from control line using Python?
Source: https://www.tutorialspoint.com/How-to-read-a-2d-array-from-a-file-in-java
0 Response to "Java Read Text File Into 2d Array of Strings"
Post a Comment