BufferedReader extends Reader. Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.The buffer size may be specified, or the default size may be used.
Constructors
Methods
Example
Reading the below File.
package com.java.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class BufferedReaderExample {
public static void main(String[] args) {
Reader reader = null;
BufferedReader br = null;
try {
reader = new FileReader("/Test/TestFolder/test-file.txt");
// Created BufferedReader with the underlying Reader
br = new BufferedReader(reader);
// Check if markSupported by BufferedReader
System.out.println("Is Mark Supported:" + br.markSupported());
if (br.markSupported()) {
// marks the current position
// 10 characters to be read before the mark position becomes invalid
br.mark(10);
}
// Skip 5 characters of data
br.skip(5);
System.out.print("After Skip File Content:");
// Checks if the stream is ready to be read
while (br.ready()) {
// Reading one character for each loop
System.out.print((char) br.read());
}
// Resets to the earlier marked position
br.reset();
System.out.println("");
System.out.print("After Reset File Content using readLine:");
while (br.ready()) {
// Using readLIne to read one line for each loop
System.out.print(br.readLine());
}
// Resetting again to the earlier marked position
br.reset();
System.out.println("");
System.out.print("Reading characters into char Array:");
char c[] = new char[10];
if (br.ready()) {
br.read(c);
for (int i = 0; i < 10; i++) {
System.out.print(c[i]);
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
// Closing the streams
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Output
Is Mark Supported:true
After Skip File Content:Data
After Reset File Content using readLine:Test Data
Reading characters into char Array:Test Data
Using lines to get a Stream
Reading the below file.
package com.java.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class BufferedReaderLinesExample {
public static void main(String[] args) {
Reader reader = null;
BufferedReader br = null;
try {
reader = new FileReader("/Test/TestFolder/test-file1.txt");
// Created BufferedReader with the underlying Reader
br = new BufferedReader(reader);
if (br.ready()) {
// Using lines
br.lines().forEach(x - > System.out.println(x));
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
// Closing the streams
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Output
Test data1
Test data2
Test data3
Related Article