Java Read file line by line

Java Read file line by line


Posted in : Core Java Posted on : July 31, 2014 at 6:58 PM Comments : [ 0 ]

In this tutorial I will teach you how to use the Java for writing a program for reading a file line by line. This is an example of efficient reading of large file line by line in Java using the BufferedReader class.

Java read file line by line - Example program in Java for reading a text line by line using the Buffered reader class

Java is know for its efficient and platform independent code. It provides the file handling API packaged in the java.io.* package. This package contains various classes and interfaces for reading and writing the files from the Java program. In this example we will use the classes and interfaces from the java.io.* package for reading a text file line by line in Java program.

We will use the BufferedReader class to read a text file in Java. The BufferedReader class has a method readLine() which reads one line at a time using the buffer. The performance of this method is good as it reads the data using the buffer.

readLine(): This of the BufferedReader class reads one line at a time using the default buffer size. You can also specify the buffered size for reading the data, but default buffer size is sufficient for almost all the general applications.

So, no need to adjust the buffer size while reading the text data though readLine() method.

Here is the complete example code of the program:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BufferedReaderExample1 {
   public static void main(String[] args) throws Exception {
      
      try{
         //Open input stream for reading the text file MyTextFile.txt
         InputStream is = new FileInputStream("data.txt");
         
         // create new input stream reader
         InputStreamReader instrm = new InputStreamReader(is);
         
         // Create the object of BufferedReader object
         BufferedReader br = new BufferedReader(instrm);
      
         String strLine;
         
         // Read one line at a time 
         while((strLine = br.readLine()) != null)
         {    
            // Print line
            System.out.println(strLine);
         }
         
      }catch(Exception e){
         e.printStackTrace();
      }
   }
}

In this section you have leaned how to read a text file in Java line by line. Check the Java - Reading a Large File Efficiently for many examples of reading file efficiently.

Read more Tutorials at File Handling in Java Tutorial Section.

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics