Modern Java uses the java.nio.file API — Path and Files.
Reading
Java
import java.nio.file.*;
import java.util.List;
Path path = Path.of("data.txt");
String content = Files.readString(path); // whole file
List<String> lines = Files.readAllLines(path); // list of lines
// large files — stream lines lazily
try (var stream = Files.lines(path)) {
stream.filter(l -> !l.isBlank())
.forEach(System.out::println);
}Writing
Java
Files.writeString(path, "Hello\n");
Files.writeString(path, "More\n", StandardOpenOption.APPEND);
Files.write(path, List.of("line 1", "line 2"));Checking and managing
Java
Files.exists(path);
Files.isReadable(path);
Files.size(path); // bytes
Files.createDirectories(Path.of("uploads/2026"));
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
Files.move(source, target);
Files.deleteIfExists(path);Building paths
Never concatenate paths with "/" — it breaks on Windows:
Java
Path p = Path.of("uploads", "2026", "photo.jpg"); // correct
Path abs = p.toAbsolutePath();
System.out.println(p.getFileName()); // photo.jpg
System.out.println(p.getParent()); // uploads/2026Walking a directory
Java
try (var paths = Files.walk(Path.of("src"))) {
paths.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith(".java"))
.forEach(System.out::println);
}Always use try-with-resources
Streams from Files.lines() and Files.walk() hold an open file handle.
Not closing them leaks handles until the process runs out.
Reading a CSV
Java
try (var lines = Files.lines(Path.of("students.csv"))) {
lines.skip(1) // header
.map(line -> line.split(","))
.forEach(cols -> System.out.println(cols[0] + " — " + cols[1]));
}For real CSV — quoted fields, embedded commas, newlines inside values —
use a library like OpenCSV rather than split(",").
Character encoding
Files.readString() uses UTF-8 by default (Java 18+ makes UTF-8 the
default everywhere). If you're reading files written by older Windows
tools, pass the charset explicitly rather than getting mojibake in your
Devanagari text.