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
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
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();
}
}
}
0 comments:
Post a Comment