NIO Files utilities read and write files in a single call.
Path tmp = Files.createTempFile("demo", ".txt");
Files.writeString(tmp, "one\ntwo\nthree");
List<String> lines = Files.readAllLines(tmp);
System.out.println("lines = " + lines.size());
System.out.println(lines.get(1));
Files.deleteIfExists(tmp);
lines = 3
two
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-26