Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › File I/O — java.io, NIO2 & Files API

What's the difference between Files.lines(), Files.readAllLines(), and Files.readString() for reading a file?

Level II · JuniorFile I/O — java.io, NIO2 & Files API
Short answer

readAllLines and readString load the entire file into memory, which is simple but dangerous for large files (OOM risk), so they're fine only when you know the file is small.

Explanation

Files.lines() returns a lazy Stream<String> that reads on demand, so it scales to huge files — but it's backed by an open file handle, so you must use it in try-with-resources or the descriptor leaks. The general rule is stream large or unbounded inputs and only slurp small, known-size files.

Common mistakes
  • Using readAllLines on multi-gigabyte files.
  • Forgetting Files.lines must be closed (it holds the file open).

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for File I/O — java.io, NIO2 & Files API.

Practise free

More on File I/O — java.io, NIO2 & Files API