๐Ÿ“ What Youโ€™ll Learn

  • How to read from and write to files
  • Difference between character and buffered streams
  • File handling best practices
  • Try-with-resources for safe closing

๐Ÿ“ฆ Working with Files

First, import the file-handling classes:

import java.io.*;

๐Ÿ“– Reading a File โ€“ FileReader & BufferedReader

try {
    BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
    String line;

    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

    reader.close();
} catch (IOException e) {
    System.out.println("Error reading file: " + e.getMessage());
}

โœ๏ธ Writing to a File โ€“ FileWriter

try {
    FileWriter writer = new FileWriter("output.txt");
    writer.write("Hello, Java File I/O!");
    writer.close();
} catch (IOException e) {
    System.out.println("Error writing file: " + e.getMessage());
}

By default, FileWriter overwrites the file. To append instead:

FileWriter writer = new FileWriter("output.txt", true);  // true = append mode

๐Ÿงผ Try-with-Resources (Auto-Close)

Java can automatically close resources like readers and writers:

try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    System.out.println("Error: " + e.getMessage());
}

๐Ÿงพ Check If File Exists

File file = new File("data.txt");
if (file.exists()) {
    System.out.println("File exists");
} else {
    System.out.println("File not found");
}

๐Ÿงฑ Other Useful File Methods

file.getName();       // file name
file.length();        // file size in bytes
file.delete();        // delete file
file.createNewFile(); // create file

๐Ÿ“˜ Recap

  • Use FileReader/BufferedReader for reading files
  • Use FileWriter to write to files (and append if needed)
  • Always handle exceptions
  • Use try-with-resources to auto-close streams