Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

buffered
reader
class
java

Methods of BufferedReader class in Java

Educative Answers Team

The BufferedReader class is used to read the text from an input stream based on characters. The class has the ability to read the data line-by-line, this makes the performance really quick.

The BufferedReader uses Buffer to read the characters. The size of the buffer is usually default, but it can be changed. The default size is usually large enough to cater to all purposes.

svg viewer

How does it work?

BufferedRead reads large portions of data from a file.txt and keeps the data in a buffer. When the next line of data is requested it is automatically retrieved from the buffer. Since there is no need to access the file again (and again), the buffer reduces computational time. The read requests are sent through Java Application which accesses the BufferedReader class.

BufferedReader class methods

Method Description
read () Used for reading a single character.
readLine() Reads one complete line.
markSupported() Used to test input stream support.
ready() Used to test whether the input stream is ready to be read.
skip() This function take a number (as a parameter) and skips that many characters.
mark() Used to mark the current position in a stream.
reset() It repositions the stream at the same position that the mark() method was last called to on the input stream.
close() It closes the input stream.

Example

The following code reads a file , “temp.txt”, line-by-line:

BufferedReaderExample.java
temp.txt
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {

	public static void main(String[] args) {

		try {
			
			BufferedReader my_Reader = new BufferedReader(new FileReader(new File(
					"temp.txt")));
			String line = "";
			while((line = my_Reader.readLine()) != null)
			{
				System.out.println(line);
			}
			my_Reader.close();
		} catch (FileNotFoundException e) {
			System.out.println("File not exists or insufficient rights");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("An exception occured while reading the file");
			e.printStackTrace();
		}

	}

}

RELATED TAGS

buffered
reader
class
java
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring