In this section, we will explore the BufferedReader and BufferedWriter classes in Java, which are used for reading and writing text from and to character streams efficiently. These classes are part of the java.io package and provide buffering capabilities to improve the performance of I/O operations.

Key Concepts

BufferedReader

  • Purpose: To read text from an input stream efficiently.
  • Buffering: It buffers the input to provide efficient reading of characters, arrays, and lines.
  • Common Methods:
    • read(): Reads a single character.
    • read(char[] cbuf, int off, int len): Reads characters into a portion of an array.
    • readLine(): Reads a line of text.

BufferedWriter

  • Purpose: To write text to an output stream efficiently.
  • Buffering: It buffers the output to provide efficient writing of characters, arrays, and strings.
  • Common Methods:
    • write(int c): Writes a single character.
    • write(char[] cbuf, int off, int len): Writes a portion of an array of characters.
    • write(String s, int off, int len): Writes a portion of a string.
    • newLine(): Writes a line separator.
    • flush(): Flushes the stream.

Practical Examples

Example 1: Reading a File Using BufferedReader

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

public class BufferedReaderExample {
    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);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • We create a BufferedReader object by wrapping a FileReader object.
  • We use a while loop to read each line of the file until readLine() returns null.
  • Each line is printed to the console.

Example 2: Writing to a File Using BufferedWriter

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterExample {
    public static void main(String[] args) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
            bw.write("Hello, World!");
            bw.newLine();
            bw.write("This is a test.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • We create a BufferedWriter object by wrapping a FileWriter object.
  • We use the write() method to write strings to the file.
  • The newLine() method is used to write a line separator.
  • The try-with-resources statement ensures that the BufferedWriter is closed automatically.

Practical Exercises

Exercise 1: Reading and Writing Files

Task: Write a program that reads from a file named input.txt and writes its content to a file named output.txt using BufferedReader and BufferedWriter.

Solution:

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

public class FileCopyExample {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("input.txt"));
             BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • We create a BufferedReader to read from input.txt.
  • We create a BufferedWriter to write to output.txt.
  • We read each line from the input file and write it to the output file, adding a new line after each line.

Common Mistakes and Tips

  • Forgetting to Close Streams: Always close your streams to free up system resources. Use try-with-resources to handle this automatically.
  • Not Handling Exceptions: Always handle IOException when performing file I/O operations.
  • Buffer Size: The default buffer size is usually sufficient, but you can specify a larger buffer size if needed for performance reasons.

Conclusion

In this section, we learned about BufferedReader and BufferedWriter, which are essential for efficient reading and writing of text in Java. We covered their key methods, practical examples, and common mistakes. Understanding these classes will help you handle file I/O operations more effectively in your Java applications. In the next section, we will delve into serialization, which allows you to convert objects into a byte stream for storage or transmission.

Java Programming Course

Module 1: Introduction to Java

Module 2: Control Flow

Module 3: Object-Oriented Programming

Module 4: Advanced Object-Oriented Programming

Module 5: Data Structures and Collections

Module 6: Exception Handling

Module 7: File I/O

Module 8: Multithreading and Concurrency

Module 9: Networking

Module 10: Advanced Topics

Module 11: Java Frameworks and Libraries

Module 12: Building Real-World Applications

© Copyright 2024. All rights reserved