VOOZH about

URL: https://mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/

⇱ How to read file in Java - BufferedReader - Mkyong.com


Skip to content

In this article, we will show you how to use java.io.BufferedReader to read content from a file

1. Files.newBufferedReader (Java 8)

In Java 8, there is a new method Files.newBufferedReader(Paths.get("file")) to return a BufferedReader

filename.txt

A
B
C
D
E
FileExample1.java

package com.mkyong;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileExample1 {

 public static void main(String[] args) {

 StringBuilder sb = new StringBuilder();

 try (BufferedReader br = Files.newBufferedReader(Paths.get("filename.txt"))) {

 // read line by line
 String line;
 while ((line = br.readLine()) != null) {
 sb.append(line).append("\n");
 }

 } catch (IOException e) {
 System.err.format("IOException: %s%n", e);
 }

 System.out.println(sb);

 }

}

Output


A
B
C
D
E

2. BufferedReader

2.1 A classic BufferedReader with JDK 1.7 try-with-resources to auto close the resources.

FileExample2.java

package com.mkyong;

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

public class FileExample2 {

 public static void main(String[] args) {

 try (FileReader reader = new FileReader("filename.txt");
 BufferedReader br = new BufferedReader(reader)) {

 // read line by line
 String line;
 while ((line = br.readLine()) != null) {
 System.out.println(line);
 }

 } catch (IOException e) {
 System.err.format("IOException: %s%n", e);
 }
 }

}

2.2 In the old days, we have to close everything manually.

FileExample3.java

package com.mkyong.calculator;

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

public class FileExample3 {

 public static void main(String[] args) {

 BufferedReader br = null;
 FileReader fr = null;

 try {

 fr = new FileReader("filename.txt");
 br = new BufferedReader(fr);

 // read line by line
 String line;
 while ((line = br.readLine()) != null) {
 System.out.println(line);
 }

 } catch (IOException e) {
 System.err.format("IOException: %s%n", e);
 } finally {
 try {
 if (br != null)
 br.close();

 if (fr != null)
 fr.close();
 } catch (IOException ex) {
 System.err.format("IOException: %s%n", ex);
 }
 }

 }

}

References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

62 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Ciprian
12 years ago

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

3
Reply
Joe James
3 years ago

Hey @mkyong, Thanks for all the wonderful work you are doing. A request if I may, would you be able to write some code to sort a csv on two columns(including datetime columns) please? I have written one and it works, but not very efficient. Thanks

1
Reply
Barun kumar
3 years ago

@mkyong could you assist??

0
Reply
Barun kumar
3 years ago

I am using bufferReader to read a 1gb file.
I do not want to keep entire file in memory until it get processed instead.

I want to keep data in memory as equal to my custom buffer size =let’s say 5*103kb where 103kb is the one line size.

When I use bufferReader.lines().count() ..I assume that it should return no’s of line=5 as my buffer size is 5*103 and each line has 103kb of text data.
But it returns the count of entire files lines I.e (1gb*1024*1024/103).

That what is use of buffer?? BufferReader.lines() do not respect the bufferSize????

Could you please help and elaborate??

Thanks,
Rk

0
Reply
Josh Ngoc
6 years ago

Thank for share buddy

0
Reply
venkatesh
7 years ago

java how to learn.. anyone tell me.. best online website

0
Reply
Anon12345
7 years ago

Thanks

0
Reply
Eswar
7 years ago

I doubt that the statement “try (BufferedReader br = new BufferedReader(new FileReader(FILENAME)))” will not close both BufferedReader and FileReader. To close both the readers, we need to use “try(FileReader fr = new FileReader(FILENAME); BufferedReader br = new BufferedReader(fr))”. Please check.

0
Reply
mkyong
7 years ago
Reply to  Eswar

Thanks, article is updated.

try (FileReader reader = new FileReader("filename.txt");
BufferedReader br = new BufferedReader(reader))

0
Reply
André
9 years ago

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!

0
Reply
mkyong
7 years ago
Reply to  André

Article is updated, thanks for your comment.

0
Reply
Biruk Wendesen
7 years ago
Reply to  André

Thank you this is anice example.

0
Reply
Moomal
12 years ago

Thanks a bunch! You just saved my day.

0
Reply
André
12 years ago

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

0
Reply
Dhanashree Makhe
12 years ago

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

0
Reply
Jane
13 years ago

HE HE HE HI

0
Reply
CJ
13 years ago

thanks you !

0
Reply
gaurav patil
8 years ago

how to open multiple file in different directory

-1
Reply
galaczi
10 years ago

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);

}

}

}

-1
Reply
k
11 years ago

it says the file is not found. what is wrong?

-1
Reply
mkyong
9 years ago
Reply to  k

Create the file manually.

0
Reply
John Jenkins
8 years ago
Reply to  mkyong

I created the file. I have used “thing.txt” and I have used “C:UsersJohnWorkspaceLunaSR2ReadFilething.txt”

0
Reply
John Jenkins
8 years ago
Reply to  John Jenkins

I created thing.txt using Eclipse

0
Reply
Justin George
11 years ago

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.

-1
Reply
Ray
11 years ago

Great and to the point, but I’m stuck on a ‘file not found’ exception because I put my file inside the src folder like this: src/res_folder/file.txt Does anyone know how to access that? I tried things like getResourceAsStream, get Resource, classloader, and putting the path as “/res_folder/file.txt” and other things but still have the same error.

-1
Reply
Ray
11 years ago
Reply to  Ray

ok, after hours and hours of looking I somehow accidentally figured it out myself, so I’ll just share it here for anyone else.
At this line: br = new BufferedReader(new FileReader(“C:\testing.txt”));
I changed it to: br = new BufferedReader(new FileReader(new File(“src/res/myfile.txt”)));

This works for me, but since I do more Android programming, I’m not sure if this is the best approach.

-1
Reply
abcd
11 years ago

Verryyyyyyyyyyyyyy Guuuddddd!!!

-1
Reply
Jens Preem
12 years ago

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?

-1
Reply
prestige
12 years ago
Reply to  Jens Preem

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;
}
}
}

0
Reply
Dara
13 years ago

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

-1
Reply
Raja
13 years ago

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

-1
Reply
Dam
13 years ago

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.

-1
Reply
Fernando
13 years ago

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

-1
Reply
srija
13 years ago
Reply to  Fernando

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

0
Reply
Muthukumar JeyaMurugan
13 years ago

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

-1
Reply
Rajesh
9 years ago

Thanks it worked for me.:)

-1
Reply
Peter
14 years ago

Finally after much searching, you answered my question, Mike !
Thanks !
There are a lot of people out in the web asking the same question.
When they and, (up till a few moments ago), myself included, try to “import” a simple text file into an Eclipse project, we were all receiving “file not found”.
Being new to Java I was amazed that this was such an “issue” for eclipse. I like Eclipse but something so fundamental, shouldn’t be so frustratingly hard. I guess the Devs are busy working on other more urgent issues and we cant complain as it is a free and in reality a good product.
Many thanks ! (c:\\testing) 🙂

-1
Reply
aljun
14 years ago

somebody help this problem …
how to read this file 1
23
45

-1
Reply
Neo
15 years ago

In your example, you should make sure to close the BufferedReader, otherwise the file may be lock not readable by some other process.

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

br.close();
…..

-1
Reply
mkyong
14 years ago
Reply to  Neo

Example is updated, with new JDK7 example.

-1
Reply
Ivan
12 years ago
Reply to  mkyong

Excelente (Y)

-2
Reply
priya
13 years ago
Reply to  mkyong

sir i want jtree tool coding for netbeans 6.9

-1
Reply
Jane
13 years ago
Reply to  priya

He he HI!

-1
Reply
muhammad adil
12 years ago
Reply to  Jane

great work done by grat man

-1
Reply
Russel
8 years ago

Di Shing

-2
Reply