How to read file in Java – BufferedReader - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline

How to read file in Java – BufferedReader

In this Java tutorial , 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
ReadFileExample.java
package com.mycareerrepublic;

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

public class ReadFileExample {

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

public static void main(String[] args) {

BufferedReader br = null;
FileReader fr = null;

try {

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

String sCurrentLine;

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

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.
ReadFileExample1.java
package com.mycareerrepublic;

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

}

}

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.