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`.
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.
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");
}
}
}Written successfullytry-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.
