beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to read file in Java using BufferedReader

By Chaitanya Singh | Filed Under: Java I/O

In this tutorial we will see two ways to read a file using BufferedReader.

Method 1: Using readLine() method of BufferedReader class.

public String readLine() throws IOException

It reads a line of text.

Method 2: Using read() method

public int read() throws IOException

It reads a character of text. Since it returns an integer value, it needs to be explicitly cast as char for reading the content of file.

Complete example

Here I have two txt files myfile.txt and myfile2.txt. In order to demonstrate both the ways to read file. I’m reading first file using readLine() method while the second file is being read using read() method.

package beginnersbook.com;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileDemo {
   public static void main(String[] args) {

       BufferedReader br = null;
       BufferedReader br2 = null;
       try{	
           br = new BufferedReader(new FileReader("B:\\myfile.txt"));		

           //One way of reading the file
	   System.out.println("Reading the file using readLine() method:");
	   String contentLine = br.readLine();
	   while (contentLine != null) {
	      System.out.println(contentLine);
	      contentLine = br.readLine();
	   }

	   br2 = new BufferedReader(new FileReader("B:\\myfile2.txt"));

	   //Second way of reading the file
	   System.out.println("Reading the file using read() method:");
	   int num=0;
	   char ch;
	   while((num=br2.read()) != -1)
	   {	
               ch=(char)num;
	       System.out.print(ch);
	   }

       } 
       catch (IOException ioe) 
       {
	   ioe.printStackTrace();
       } 
       finally 
       {
	   try {
	      if (br != null)
		 br.close();
	      if (br2 != null)
		 br2.close();
	   } 
	   catch (IOException ioe) 
           {
		System.out.println("Error in closing the BufferedReader");
	   }
	}
   }
}

References:

  • BufferedReader JavaDoc

Enjoyed this post? Try these related posts

  1. How to rename file in Java – renameTo() method
  2. How to read file in Java – BufferedInputStream
  3. How to write to a file in java using FileOutputStream
  4. How to write to file in Java using BufferedWriter
  5. How to check if a File is hidden in Java
  6. How to get the last modified date of a file in java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap