Java ยท Chapter 33 of 42

Java Files

Java provides classes like File, FileReader, FileWriter, and the newer java.nio.file.Files for reading from and writing to files on disk.

File operations can throw checked IOExceptions, so they are typically wrapped in try-catch blocks or declared with `throws IOException`.

Syntax
try (FileWriter w = new FileWriter("file.txt")) {
  w.write("text");
}

Reading and writing files

FileWriter and BufferedWriter write text to files; FileReader, BufferedReader, or Scanner read text from files line by line or token by token.

try-with-resources

try-with-resources automatically closes file resources like readers and writers, even if an exception occurs, preventing resource leaks.

Example 1 (java)
import java.io.FileWriter;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    try (FileWriter writer = new FileWriter("output.txt")) {
      writer.write("Hello, File!");
      System.out.println("Written successfully");
    } catch (IOException e) {
      System.out.println("An error occurred");
    }
  }
}
Output
Written successfully

try-with-resources writes to a file and automatically closes the writer afterward.

Key points

  • FileWriter and FileReader handle basic text file I/O.
  • try-with-resources auto-closes file resources.
  • File operations can throw checked IOException.
  • java.nio.file.Files offers modern, convenient file utilities.
๐Ÿ’ก Note: Always close file resources โ€” try-with-resources is the safest and most concise way to do this.

๐Ÿ“ Quick Quiz

1. What exception type do file operations typically throw?

2. What does try-with-resources automatically do?

3. Which class writes text to a file?