Command Palette

Search for a command to run...

Back to the lesson: Topic 12.3 — Path and Files (NIO.2)
Core Java · Example 2 of 3 Java 11+

Block path traversal

resolve() with an absolute path returns that path unchanged, so the startsWith check is what stops "/etc/passwd". This is a defence; also allow-list expected names in real code.

Path is an object that names a file or folder, and Files is a class of static methods that act on the file system: read, write, copy, move, delete, list and inspect. Together (NIO.2, Java 7, with Files.readString/writeString and Path.of added in Java 11) they replace the old java.io.File for all new code.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static String extension(Path p) that returns the file extension in lower case ("" if none), using only getFileName() and String methods. Test it with report.PDF, archive.tar.gz, README and .gitignore.

02

Given the base Path.of("site") and the paths site/index.html, site/blog/post.html and site/img/logo.png, print each one relative to the base, with / separators.

03

Write static Path backupName(Path original, int n) that turns docs/plan.txt into docs/plan.txt.1 style siblings for n = 1 and n = 2, using resolveSibling. Print both with / separators.

Explain it without notes

01

What's the difference between Path and Files, and why did NIO.2 replace java.io.File?

02

Which Files methods load a whole file into memory, and which stream it? When would you use each?

03

Why must Files.lines, Files.list and Files.walk be closed, when Files.readAllLines doesn't need to be?

04

How do you write a file so that a crash or a concurrent reader never sees a half-written version?

05

How do you safely serve a file whose name comes from a user?

Block path traversal Java 11+
Sign in to run this example in your browser.

Expected output

ALLOW  cat.png  ->  uploads/cat.png
ALLOW  2024/report.pdf  ->  uploads/2024/report.pdf
ALLOW  a/../dog.png  ->  uploads/dog.png
REJECT ../secrets.txt
REJECT a/../../etc/passwd
REJECT /etc/passwd