by

text to two dimensional array

Here we parse a text or csv file to a two dimensional array. By adding the TextReader class to your project, you just need to initialize that class like it is done in the main class. Enjoy!
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/237891/text-to-two-dimensional-array?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
// Converter class package com.laurenthinoul.main; import java.io.*; import java.nio.charset.Charset; public class TextReader { //Here we give the location of the text file as a String and we return a two dimensional array public int[][] parseFileToArray(String file) throws IOException { int numberOfRows = getNumberOfCols(file); return parseToArray(file, numberOfRows); } //wee need to count the cols of the text to initialize the two dimensional array private int getNumberOfCols(String file) throws IOException { InputStream is = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); int count = 0; while (br.readLine() != null) { count++; } br.close(); is.close(); return count; } //we read the text and parse it to the two dimensional array private int[][] parseToArray(String file, int numberOfRows) throws IOException { InputStream is = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String line; int[][] myArray = new int[numberOfRows][]; int row = 0; while ((line = br.readLine()) != null) { //here we say the line must be split by tab. Change it to your wanted character. String[] nums = line.split("\t"); myArray[row] = new int[nums.length]; for (int col = 0; col < nums.length; col++) { int n = Integer.parseInt(nums[col]); myArray[row][col] = n; } row++; } br.close(); is.close(); return myArray; } } //the main class package com.laurenthinoul.main; import java.io.*; import java.nio.charset.Charset; public class ReadText { public static void main(String args[]) throws IOException { final String file = "/Users/laurenthinoul/.../afile.txt"; TextReader reader = new TextReader(); int[][] myArray = reader.parseFileToArray(file); for(int i = 0; i < myArray.length; i++){ for(int j = 0; j < myArray[i].length; j++){ System.out.println("["+i+"]["+j+"] = "+myArray[i][j]); } } } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus