Tuesday, June 14, 2011

Read text file into 2D array - Java

The text file is read line by line.

String array[x][y] ;

x - xth line in text file
y - yth word

So

array[x][y] - yth word in xth line

Here is the code

 static void readTo2DArray() throws IOException {

  FileInputStream fstream = new FileInputStream("test.txt");
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));

  String strLine;
  int arraySize = 6;
  String array[][] = new String[arraySize][];
  int index = 0;
  while ((strLine = br.readLine()) != null) {
   
   if (index >= arraySize - 1) {
    System.out.println("Error : Increase array size !");
    break;
   }
   array[index] = strLine.split(" ");
   index++;
   
  }

  printAll(array);

 }

 static void printAll(String array[][]) {

  for (int i = 0; i < array.length; i++) {

   if (array[i] != null) {
    for (int j = 0; j < array[i].length; j++) {
     System.out.print(array[i][j] + " ");
    }
    System.out.println(" ");
   }
  }

 }



A FileInputStream is used to read raw bytes of the specified file and hence it is used to
instantiate  a DataInputStream. A DataInputStream faciliates to read primitive data types 
from the FileInputStream and it is done so in an machine independent manner. And the 
infamous BufferedReader provides the basis  for reading bytes from the DataInputStream in 
blocks rather than reading them byte by byte. It improves the read efficiency significantly 
and it is the industry standard of reading data.


No comments:

Post a Comment