HOME HTML EDITOR C JAVA PHP

Java BufferedReader Methods

In Java, BufferedReader is used to read text from a file efficiently. It reads characters, arrays, and lines. It is faster than FileReader because it uses buffering.

The BufferedReader class belongs to the java.io package.

1. Importing BufferedReader

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

2. Creating a BufferedReader Object

To read data from a file, we create a BufferedReader object with FileReader.

BufferedReader br = new BufferedReader(new FileReader("example.txt"));

3. read()

The read() method reads a single character. It returns -1 when the end of file is reached.

int data; while((data = br.read()) != -1) { System.out.print((char) data); } br.close();

4. readLine()

The readLine() method reads a complete line of text. It returns null when the end of file is reached.

String line; while((line = br.readLine()) != null) { System.out.println(line); } br.close();

5. ready()

The ready() method checks if the stream is ready to be read.

System.out.println(br.ready());

6. skip()

The skip() method skips a specified number of characters.

br.skip(5); // skips first 5 characters

7. close()

The close() method closes the stream and releases system resources.

br.close();

Complete Example with Exception Handling

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Main { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader("example.txt")); String line; while((line = br.readLine()) != null) { System.out.println(line); } br.close(); } catch (IOException e) { System.out.println("An error occurred."); } } }

Why BufferedReader is Faster?

Difference Between FileReader and BufferedReader

Important Points

Conclusion

The BufferedReader class provides methods like read(), readLine(), skip(), ready(), and close().

It is widely used for reading text files efficiently.

Tip: Use BufferedReader when you need fast and efficient text file reading.