Fatskills
Practice. Master. Repeat.
Study Guide: Java: Input-Output - File I/O, FileReader, FileWriter, BufferedReader, PrintWriter
Source: https://www.fatskills.com/java-programming/chapter/java-input-output-file-io-filereader-filewriter-bufferedreader-printwriter

Java: Input-Output - File I/O, FileReader, FileWriter, BufferedReader, PrintWriter

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~5 min read

What This Is and Why It Matters

File I/O in Java involves reading from and writing to files using classes like FileReader, FileWriter, BufferedReader, and PrintWriter. Mastering these concepts is crucial for handling data persistence, logging, and configuration management in applications. Incorrect usage can lead to data loss, application crashes, or security vulnerabilities. For instance, improper file handling can cause data corruption, making your application unreliable.

Core Knowledge (What You Must Internalize)

  • FileReader: Reads text from a file (why this matters: essential for reading configuration files or logs).
  • FileWriter: Writes text to a file (why this matters: necessary for logging, saving user data).
  • BufferedReader: Reads text from a character-input stream, buffering characters for efficient reading (why this matters: improves performance by reducing I/O operations).
  • PrintWriter: Writers formatted representations of objects to a text-output stream (why this matters: simplifies writing formatted text to files).
  • Character Streams vs Byte Streams: Character streams handle 16-bit Unicode, while byte streams handle raw binary data (why this matters: choose the right stream type for your data).
  • FileNotFoundException: Thrown when a file with the specified pathname does not exist (why this matters: handle this exception to avoid runtime errors).
  • IOException: Thrown when an I/O operation (reading or writing) fails (why this matters: handle this exception to manage I/O errors gracefully).

Step?by?Step Deep Dive

  1. Reading from a File using FileReader and BufferedReader
  2. Action: Create instances of FileReader and BufferedReader.
  3. Principle: FileReader reads raw characters, while BufferedReader buffers them for efficiency.
  4. Example: java FileReader fileReader = new FileReader("example.txt"); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close();
  5. Common Pitfall: Forgetting to close the reader can lead to resource leaks.

  6. Writing to a File using FileWriter and PrintWriter

  7. Action: Create instances of FileWriter and PrintWriter.
  8. Principle: FileWriter writes raw characters, while PrintWriter formats them.
  9. Example: java FileWriter fileWriter = new FileWriter("output.txt"); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.println("Hello, World!"); printWriter.close();
  10. Common Pitfall: Not closing the writer can result in incomplete writes.

  11. Handling Exceptions

  12. Action: Use try-with-resources to automatically close streams.
  13. Principle: Proper exception handling prevents runtime errors.
  14. Example: java 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(); }
  15. Common Pitfall: Ignoring exceptions can hide critical issues.

  16. Appending to a File

  17. Action: Use the FileWriter constructor with the append flag.
  18. Principle: Appending adds data to the end of the file without overwriting.
  19. Example: java FileWriter fileWriter = new FileWriter("output.txt", true); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.println("Appended text"); printWriter.close();
  20. Common Pitfall: Forgetting the append flag will overwrite the file.

How Experts Think About This Topic

Experts view file I/O as a critical component of application stability and performance. They focus on efficient resource management, proper exception handling, and choosing the right stream type for the task. Instead of memorizing methods, they understand the underlying principles of buffering and formatting.

Common Mistakes (Even Smart People Make)

  1. The mistake: Not closing streams.
  2. Why it's wrong: Leads to resource leaks and potential data loss.
  3. How to avoid: Use try-with-resources.
  4. Exam trap: Questions that involve long methods without resource management.

  5. The mistake: Ignoring exceptions.

  6. Why it's wrong: Hides critical errors.
  7. How to avoid: Always handle IOException and FileNotFoundException.
  8. Exam trap: Code snippets without exception handling.

  9. The mistake: Using the wrong stream type.

  10. Why it's wrong: Can cause data corruption or inefficiency.
  11. How to avoid: Understand the difference between character and byte streams.
  12. Exam trap: Questions that mix stream types.

  13. The mistake: Forgetting the append flag.

  14. Why it's wrong: Overwrites existing data.
  15. How to avoid: Always specify the append flag when needed.
  16. Exam trap: Code snippets that require appending data.

Practice with Real Scenarios

Scenario: You need to read a configuration file and print its contents. Question: Write the code to read "config.txt" and print each line. Solution:

try (BufferedReader br = new BufferedReader(new FileReader("config.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Answer: The code reads and prints each line of "config.txt". Why it works: BufferedReader efficiently reads the file line by line.

Scenario: You need to log user actions to a file. Question: Write the code to append "User logged in" to "log.txt". Solution:

try (FileWriter fw = new FileWriter("log.txt", true);
     PrintWriter pw = new PrintWriter(fw)) {
    pw.println("User logged in");
} catch (IOException e) {
    e.printStackTrace();
}

Answer: The code appends "User logged in" to "log.txt". Why it works: FileWriter with the append flag adds data to the file.

Quick Reference Card

  • Core rule: Always close streams to prevent resource leaks.
  • Key formula: Use try-with-resources for automatic resource management.
  • Critical facts:
  • FileReader and FileWriter handle raw characters.
  • BufferedReader and PrintWriter improve efficiency and formatting.
  • Handle IOException and FileNotFoundException.
  • Dangerous pitfall: Ignoring exceptions can hide critical errors.
  • Mnemonic: "Close streams, handle exceptions, choose the right type."

If You're Stuck (Exam or Real Life)

  • What to check first: Verify that streams are closed and exceptions are handled.
  • How to reason from first principles: Understand the difference between character and byte streams.
  • When to use estimation: Estimate the size of data to choose the right buffering strategy.
  • Where to find the answer: Refer to the Java API documentation for stream classes.

Related Topics

  • Serialization: Learn how to convert objects to byte streams for persistent storage.
  • NIO (New I/O): Explore non-blocking I/O operations for improved performance.