Reading text files in JAVA

I used the below given code to read a text file(data.txt) during one of my course works for JAVA as it was a requirement for that course work. And thought it will be usefull for many others in carrying out various other projects as well.

Getting into to the code first up you need to import two classes, BufferedReader and FileReader in my case i have used the main method itself to read the file if you wanna read it more than once the recommended way is to introduce a new function to read the file since, it would be the professional approach to get on with it

And you will also note that I have used the split() function to a good use here using an array of string called “tkn” which takes all the required fields from the text file where ever it comes across a (,) in  a particular line. Hence, you can manipulate all those elements seperately later in your programme.

import java.io.BufferedReader;
import java.io.FileReader; public class ReadText
{
 public static void main(String args[])
 {

  try
 {

  FileReader fread=null;
  BufferedReader bread = new BufferedReader(new FileReader(”data.txt”));

  String line;
  while((line=bread.readLine())!=null)
  {
   String[] tkn =line.split(“,”);
   for(int i=0; i<tkn.length;i++)
   {
    System.out.println(tkn[i]);

   }
 }

}

catch(Exception e)
{
     System.out.println(”Exception: ” + e);
}

} //end of main()

} //end of class ReadText

Advertisements