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

Why should you prefer Path.resolve and avoid string concatenation for file paths, and what's the security angle?

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

Building paths by string concatenation hardcodes separators (breaking cross-platform) and is error-prone, whereas Path.resolve and the Paths/Path API handle separators and normalization correctly.

Explanation

The security angle is path traversal: if you join user input naively, a value like '../../etc/passwd' escapes your intended directory. The defense is to resolve against a known base, call normalize(), and then verify the result still startsWith the base directory before touching the file.

Common mistakes
  • Building paths with string concatenation and '/' separators.
  • Not normalising user paths, which allows ../ path traversal.

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