The `BufferedReader` and `BufferedWriter` classes in Java provide a way to read and write text efficiently by using a buffer to reduce the number of I/O operations. These classes are often used when reading and writing large amounts of text data. Here are some basics of `BufferedReader` and `BufferedWriter` in Java:
1. BufferedReader: The `BufferedReader` class provides a way to read text from a character input stream, such as a `FileReader`, in a buffered manner. For example:
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) { String line; while ((line = reader.readLine()) != null) { // Process the line } } catch (IOException e) { // Handle the exception }
Here, a `BufferedReader` is used to read lines of text from the file “file.txt” in a buffered manner. The `readLine()` method reads a line of text from the input stream and returns it as a string.
2. BufferedWriter: The `BufferedWriter` class provides a way to write text to a character output stream, such as a `FileWriter`, in a buffered manner. For example:
try (BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"))) { String line = "Hello, world!"; writer.write(line); writer.newLine(); } catch (IOException e) { // Handle the exception }
Here, a `BufferedWriter` is used to write a line of text to the file “file.txt” in a buffered manner. The `write()` method writes a string of text to the output stream, and the `newLine()` method writes a newline character.
3. Flushing the buffer: When using `BufferedReader` and `BufferedWriter`, it is important to flush the buffer to ensure that all data is written to the output stream or read from the input stream. The `flush()` method is used to flush the buffer. For example:
try (BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"))) { String line = "Hello, world!"; writer.write(line); writer.newLine(); writer.flush(); // Flush the buffer } catch (IOException e) { // Handle the exception }
Here, the `flush()` method is called to ensure that all data is written to the file “file.txt”.
Using `BufferedReader` and `BufferedWriter` can improve the performance of text I/O operations in Java. By understanding the basics of these classes, you can write more efficient and effective code that can handle large amounts of text data in your applications.