Coding Techniques
File Handling, IO and NIO · Study material
Processing big files lazily with Files.lines
Files.lines returns a Stream that reads the file line by line, so even very large files can be filtered and summarised with little memory.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
Path log = Files.createTempFile("app", ".log");
Files.writeString(log, """
INFO server started
WARN disk 80% full
INFO user asha logged in
ERROR db timeout
INFO user ravi logged in
ERROR payment failed
""");
// Files.lines reads LAZILY, one line at a time – good for big files; close it with try-with-resources
try (Stream<String> lines = Files.lines(log)) {
Map<String, Long> byLevel = lines.filter(l -> !l.isBlank())
.collect(Collectors.groupingBy(l -> l.split("\\s+")[0], TreeMap::new, Collectors.counting()));
System.out.println(byLevel);
}
try (Stream<String> lines = Files.lines(log)) {
System.out.println(lines.filter(l -> l.startsWith("ERROR")).map(l -> l.substring(6)).toList());
}
Files.delete(log);
}
}
{ERROR=2, INFO=3, WARN=1}
[db timeout, payment failed]PrintWriter and Scanner
PrintWriter brings print, println and printf to any writer; Scanner reads tokens and numbers from a file or any input.
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("report", ".txt");
try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(file))) { // printf / println to a file
pw.printf("%-6s %5s%n", "item", "qty");
pw.printf("%-6s %5d%n", "pen", 120);
pw.printf("%-6s %5d%n", "book", 45);
pw.println("total " + (120 + 45));
}
System.out.print(Files.readString(file));
try (Scanner sc = new Scanner(file)) { // Scanner tokenises a file
sc.nextLine(); // skip the header
int sum = 0;
while (sc.hasNext()) {
String word = sc.next();
if (word.equals("total")) System.out.println("check total = " + sc.nextInt());
else if (sc.hasNextInt()) sum += sc.nextInt();
}
System.out.println("summed " + sum);
}
Files.delete(file);
}
}
item qty pen 120 book 45 total 165 check total = 165 summed 165
Legacy java.io.File vs NIO
// Legacy (still common in old code)
File f = new File("data/report.txt");
boolean ok = f.delete(); // just returns false on failure – no reason given
File[] children = new File("data").listFiles();
// Modern NIO.2
Path p = Path.of("data", "report.txt");
Files.delete(p); // throws NoSuchFileException, AccessDeniedException … with details
try (Stream<Path> s = Files.list(Path.of("data"))) { … }
// Converting between them
Path fromFile = f.toPath();
File fromPath = p.toFile(); File handling checklist
- Use Path and Files for new code.
- Open every stream, reader and writer in try-with-resources.
- State the charset (UTF-8) explicitly when converting bytes and text.
- Buffer readers and writers; stream big files instead of loading them whole.
- Close Files.lines/list/walk streams.
- Build paths with resolve, never string concatenation.
- Handle IOException with a clear message; do not swallow it.
- Write to a temporary file and move it into place for safe updates.