Java File Manipulation: How to Read and Write Files Using FileReader, FileWriter, and BufferedReader

Java File Manipulation: How to Read and Write Files Using FileReader, FileWriter, and BufferedReader

File Manipulation in Java – Reading and Writing Data

File manipulation is a fundamental skill for Java developers, enabling applications to read from and write to external files. Java provides robust classes such as FileReader, FileWriter, and BufferedReader to handle file operations efficiently. Whether you are dealing with text files, logs, or configuration files, mastering these classes is crucial.

In this guide, you’ll learn:

  • How to read and write files in Java using FileReader, FileWriter, and BufferedReader.
  • Best practices for file manipulation and resource management.
  • Real-world examples and common pitfalls to avoid.

📖 Learn more: Oracle Java I/O Documentation


Why is File Manipulation Important in Java?

File manipulation allows Java applications to:

  • Store data persistently, beyond the application’s lifecycle.
  • Read configurations from external files.
  • Log application activities for debugging and monitoring.
  • Exchange data with other systems using text files or CSV files.

📖 Read more: GeeksforGeeks – File Handling in Java


Reading Files in Java

1. Using FileReader and BufferedReader

FileReader is a character stream class used to read data from text files, while BufferedReader provides buffering for efficient reading.

Example: Reading a File Line by Line

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

public class ReadFileExample {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. Using FileInputStream for Binary Files

For binary files, use FileInputStream, which reads bytes instead of characters.

import java.io.FileInputStream;
import java.io.IOException;

public class ReadBinaryFile {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("image.png")) {
            int byteData;
            while ((byteData = fis.read()) != -1) {
                System.out.print((char) byteData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

📖 Learn more: W3Schools – Java FileReader


Writing Files in Java

1. Using FileWriter

The FileWriter class is used to write data to text files. It can overwrite or append data to an existing file.

Example: Writing to a File

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

public class WriteFileExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("example.txt", true)) { // true = append mode
            writer.write("Hello, this is a new line!\n");
            System.out.println("Data written successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. Using FileOutputStream for Binary Files

For binary data, use FileOutputStream.

import java.io.FileOutputStream;
import java.io.IOException;

public class WriteBinaryFile {
    public static void main(String[] args) {
        try (FileOutputStream fos = new FileOutputStream("output.dat")) {
            fos.write("Binary Data".getBytes());
            System.out.println("Binary data written successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

📖 Read more: Baeldung – Writing Files in Java


Best Practices for File Manipulation in Java

  1. Always Close Resources: Use try-with-resources to automatically close streams.
  2. Use Buffered Streams: BufferedReader and BufferedWriter are more efficient for large files.
  3. Handle Exceptions Gracefully: Always catch IOExceptions and provide meaningful messages.
  4. Avoid Hardcoding File Paths: Use relative paths or externalize paths in configuration files.
  5. Check File Existence: Before reading or writing, verify that the file exists.

Frequently Asked Questions (FAQ)

1. What is the difference between FileReader and BufferedReader in Java?

  • FileReader is used for reading characters from text files.
  • BufferedReader adds buffering, allowing efficient reading of large files or line-by-line reading.

2. How do I append data to an existing file in Java?

Use FileWriter with append mode enabled:

new FileWriter("example.txt", true);

The true parameter ensures that data is appended instead of overwritten.

3. Can I read binary files using FileReader in Java?

No, FileReader is for text files only. Use FileInputStream for binary data.

4. What is the try-with-resources statement?

This statement automatically closes resources (e.g., streams) at the end of execution, improving resource management and reducing memory leaks.

5. How do I handle exceptions when working with files in Java?

Always wrap file operations in try-catch blocks and log exceptions for debugging purposes.


Conclusion

File manipulation in Java is a crucial skill for data persistence, configuration management, and file-based data exchange. By mastering FileReader, FileWriter, and BufferedReader, you can handle text and binary files efficiently and avoid common pitfalls.

🚀 Now that we know how to manipulate files, let’s explore the world of collections in Java!

Scroll to Top