How to read file in Java – BufferedReader

In Java, you can use java.io.BufferedReader to read content from a file.

Note
There are many ways to read a file, but this BufferedReader is the simplest and most common-used method.

1. Classic BufferedReader

A classic BufferedReader to read content from a file.

E:\\test\\filename.txt

This is the content to write into file
This is the content to write into file
ReadFileExample1.java

package com.mkyong;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample1 {

	private static final String FILENAME = "E:\\test\\filename.txt";

	public static void main(String[] args) {

		BufferedReader br = null;
		FileReader fr = null;

		try {

			//br = new BufferedReader(new FileReader(FILENAME));
			fr = new FileReader(FILENAME);
			br = new BufferedReader(fr);

			String sCurrentLine;

			while ((sCurrentLine = br.readLine()) != null) {
				System.out.println(sCurrentLine);
			}

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {

				if (br != null)
					br.close();

				if (fr != null)
					fr.close();

			} catch (IOException ex) {

				ex.printStackTrace();

			}

		}

	}

}

Output :


This is the content to write into file
This is the content to write into file

2. JDK7 Example

try-with-resources example to auto close the file reader.

ReadFileExample2.java

package com.mkyong;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample2 {

	private static final String FILENAME = "E:\\test\\filename.txt";

	public static void main(String[] args) {

		try (BufferedReader br = new BufferedReader(new FileReader(FILENAME))) {

			String sCurrentLine;

			while ((sCurrentLine = br.readLine()) != null) {
				System.out.println(sCurrentLine);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

References

  1. The try-with-resources Statement
  2. How to append content to file in Java
  3. BufferedReader JavaDoc
  4. How to write to file in Java – BufferedWriter

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
mahanta chauhan
Guest
mahanta chauhan

Why br is initialized twice?

I am groot
Guest
I am groot

fdbfd

Justin George
Guest
Justin George

Very Good article. Is there a way to access folder using authenitcation. Right now I’m using smb api for this. But it would be easier if the authentication can be done in this program.

Raja
Guest
Raja

Hi, your codes works fine but i am getting an encrypted version, so how can i get non-encrypted version.

Russel
Guest
Russel

Di Shing

Deepak Murthy
Guest
Deepak Murthy

Thank you for this blog, you have a very good coding style.
It helped me to pick up the code easily.

Emilio
Guest
Emilio

can someone explain me why do i have to create a FileReader object containing the file and then the bufferedreader containing the FileReader i just created rather than just creating the bufferedreader with the file?

i mean why this:
FileReader f=new FileReader(file);
BufferedReader b= new BufferedReader(f);

rather than this:
BufferedReader b= new BufferedReader(b);

thanks in advance.

gaurav patil
Guest
gaurav patil

how to open multiple file in different directory

André
Guest
André

Excelent!
just for comment, in your first example, the line
“br = new BufferedReader(new FileReader(FILENAME));”
wasn’t necessary!

Thank you!
I learn a lot with you!

galaczi
Guest
galaczi
public Ceg(String file) { Scanner scanner = null; try { scanner = new Scanner(new File(file)); } catch (FileNotFoundException ex) { System.out.println(“Allomany megnyitasi hiba!!”); System.exit(1); } while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.length() != 0) { System.out.println(“***Line: ” + line); StringTokenizer stk = new StringTokenizer(line, “, .;:?!”); int id = Integer.parseInt(stk.nextToken()); String vezeteknev = stk.nextToken(); String keresztnev = stk.nextToken(); int eletkor = Integer.parseInt(stk.nextToken()); String beosztas = stk.nextToken(); Alkalmazott a = new Alkalmazott(id, vezeteknev, keresztnev, eletkor, beosztas); this.alkalmazott.add(a); } } }
abcd
Guest
abcd

Verryyyyyyyyyyyyyy Guuuddddd!!!

Timothy Jlay
Guest
Timothy Jlay

hi I am very new to java and I would like to know how to write a program that would move multiple files from a different folder, delete the files from the previous folder and copy and rename those files in another folder

disqus_mLsYNn89SO
Guest
disqus_mLsYNn89SO

sssssssssssssssssss

karthik
Guest
karthik

you are printing –

System.out.println(sCurrentLine);

what if i want to store them in string array ?

Kashey
Guest
Kashey

String [] aray = new String[10]; // 10 for example

try (BufferedReader br = new BufferedReader(new FileReader(“C:\testing.txt”)))
{

String sCurrentLine;
int count = 0;
while ((sCurrentLine = br.readLine()) != null) {
array[count++] = sCurrentLine;
}

} catch (IOException e) {
e.printStackTrace();
}

Ciprian
Guest
Ciprian

Very good and “to the point” article! Congrats!

Moomal
Guest
Moomal

Thanks a bunch! You just saved my day.

André
Guest
André

Congratulations, for your posts, is has helped me a lot!

Dhanashree Makhe
Guest
Dhanashree Makhe

Hello sir pls send me code of BufferReader…Sir please…

RAI
Guest
RAI

how can I read .txt in java web

Gowtham
Guest
Gowtham

Hii,
try (BufferedReader br = new BufferedReader(new FileReader(“C:\testing.txt”))),

how to close this connection in finally? or else it will automatically closes.

jenny
Guest
jenny

hii!concerning the hangman game .. i am trying to write a method that reads a file then adds a word and its hint to the file but taking into consideration that this word should not exist in the file any help ?

priya
Guest
priya

can anyone say how to write a java code for wordnet that it should read the text file and display the synonyms for each word.

Anand Kumar
Guest
Anand Kumar

can get complete file operations using java code here – http://www.javadiscover.com/search/label/File

Jens Preem
Guest
Jens Preem

What if when I want to read in file not from newline to newline but from some other token to token? Like from LABEL to LABEL etc. What tool should I use then?

prestige
Guest
prestige
i guess u have to use Scanner to read the file. public class readFile { public static void main(String args[]) { File f = new File(filePath); Scanner read = new Scanner(f).useDelimeter(“put anything as a delimeter eg: ##”); String content =read.next(); while((content=read.next()).hasNext()) { content += content; } } }
Dara
Guest
Dara

Itis a very good code. I alos have written some tips in Java for file access and manipulation including reading, writing, creating file, and folder,…http://www.worldbestlearningcenter.com/tips/Java-write-file.htm

trackback
Reading reading a text file in Java | Java Programming
Jane
Guest
Jane

HE HE HE HI

CJ
Guest
CJ

thanks you !

Dominik
Guest
Dominik

Hi.

Thank you.

Good bye.

Jane
Guest
Jane

Hi, Goodbye, Thankyou, what the heck???
:( otherwise known as :(((

Nick
Guest
Nick

It is a really weird saying, I have to agree with that.

Dam
Guest
Dam

How can you adapt the code to allow the variable “sCurrentline”, to be manipulated through methods such as, .split(), out side of the try-catch statement. It will not even print “sCurrentLine”, unless it is in side the try-catch statement.

Fernando
Guest
Fernando

Hi, where the txt file should be placed??
I created a txt file on the same folder of the java files and the application always throw the FileNotFoundException. I tried different names, different format files, but it never finds the file.

Thanks

srija
Guest
srija

you can save it anywhere but you have to save it with .java extension

Muthukumar JeyaMurugan
Guest
Muthukumar JeyaMurugan

The entire Java File Operation like Reading, writing, Delete are found here,
http://antguider.blogspot.in/2012/06/java-file-operation.html

Rajesh
Guest
Rajesh

Thanks it worked for me.:)