File Handling in Java
File handling lets a program read data from files and write data that can be used later. A path identifies a file or directory. Opening, reading, and writing can fail, so programs also need to handle errors and close resources.
Why Do We Need This?
A practice app may keep notes in a text file. It needs to choose where the file is located, how text is encoded, and whether writing should replace or append to existing contents.
Main Ideas
| Concept | What it means |
|---|---|
| Path | Represents a filesystem path |
| Files | Provides operations such as reading, writing, and checking files |
| Text encoding | Defines how characters are represented as bytes |
| Try-with-resources | Closes opened resources even when an operation fails |
| Serialization | Converts supported object state to a byte representation |
Simple Working Example
Run this program on its own. All required imports and classes are included.
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
public class HelloWorld {
public static void main(String[] args) throws Exception {
Path notes = Files.createTempFile("java-notes-", ".txt");
try {
Files.write(notes, Collections.singletonList("Practice one example"),
StandardCharsets.UTF_8);
for (String line : Files.readAllLines(notes, StandardCharsets.UTF_8)) {
System.out.println(line);
}
} finally {
Files.deleteIfExists(notes);
}
}
}Output
Practice one exampleThe program creates its own temporary input file, writes one line, reads it, and removes it. readAllLines is convenient for this tiny example; use gradual reading for large files.
Topics in This Section
Easy Way to Remember
Choose the path, encoding, and resource lifetime deliberately. A file example should state which input files it needs and which files it creates.
See you in next page....??