Unit 11: File Input and Output

File Input and Output in Java


Introduction to File I/O

The capability to read data from files and write data to files is a foundational skill for any programmer. Java provides robust utilities to handle file operations, ensuring data can be persisted and retrieved as needed.


Foundations of File I/O

Streams: Gateways to Files

In Java, streams are sequences of data. There are two main types:

  • InputStream – Reads data from a source.
  • OutputStream – Writes data to a destination.

Files in Java are dealt with using streams, which are provided by the java.io package.


Reading from a File

The FileReader Class

The FileReader class is used to read character files. Its primary methods are:

  • read(): Reads a single character.
  • close(): Closes the reader.

Example:

try {
    FileReader reader = new FileReader("filename.txt");
    int character;
    while ((character = reader.read()) != -1) {
        System.out.print((char) character);
    }
    reader.close();
} catch (IOException e) {
    e.printStackTrace();
}

Writing to a File

The FileWriter Class

The FileWriter class is used to write characters to a file:

  • write(String): Writes a string to the file.
  • close(): Closes the writer.

Example:

try {
    FileWriter writer = new FileWriter("filename.txt");
    writer.write("Hello, World!");
    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

Pro Tip!

Always close streams after using them to free up system resources!


Handling Exceptions

File operations can fail for various reasons like the file not being found or not having permission to read/write. Java's exception handling is crucial here:

  • FileNotFoundException: Thrown when trying to access a non-existent file.
  • IOException: Thrown on a failed or interrupted I/O operation.

Buffers: Efficient File Operations

Reading or writing character by character can be slow. Java provides buffered classes for more efficient operations:

  • BufferedReader
  • BufferedWriter

These classes read/write text from/to character-output streams, buffering characters for better performance.


Summary

File I/O in Java is a core skill, enabling data persistence beyond a program's run time. With the power of streams and the utility of the java.io package, managing files becomes a streamlined process.


References


AP CSA Homework Assignment

Assignment: Diary Keeper

Instructions

  1. Create a simple diary application where users can:
    • Add new diary entries with dates.
    • Read existing diary entries.
    • Update or delete entries.
  2. Use file operations to persist this data, ensuring entries remain even after the program is closed.
  3. Implement exception handling for potential file errors.
  4. Reflect: Discuss the challenges faced during the implementation. How can the application be improved?
Previous
Exception Handling