The Buffered Streams BufferedReader - RameshMF/java-io-guide GitHub Wiki
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
BufferedInputStream class is used to read buffered byte stream that is raw byte. BufferedReader class is used to read character stream.
In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
- BufferedReader(Reader in) - Creates a buffering character-input stream that uses a default-sized input buffer.
- BufferedReader(Reader in, int sz) - Creates a buffering character-input stream that uses an input buffer of the specified size.
- void close() - Closes the stream and releases any system resources associated with it.
- Stream lines() - Returns a Stream, the elements of which are lines read from this BufferedReader.
- void mark(int readAheadLimit) - Marks the present position in the stream.
- boolean markSupported() - Tells whether this stream supports the mark() operation, which it does.
- int read() - Reads a single character.
- int read(char[] cbuf, int off, int len) - Reads characters into a portion of an array.
- String readLine() - Reads a line of text.
- boolean ready() - Tells whether this stream is ready to be read.
- void reset() - Resets the stream to the most recent mark.
- long skip(long n) - Skips characters.
This program reads a text file named "sample.txt" and print output to console. The "sample.txt" contains below text in it.
This is the text content
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* The class demonstrate the usage of BufferedReader class methods.
* @author javaguides.net
*
*/
public class BufferedReaderExample {
public static void main(String[] args) {
try (FileReader fr = new FileReader("sample.txt");
BufferedReader br = new BufferedReader(fr);) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
This is the text content