Command Palette

Search for a command to run...

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

Path anatomy, no disk needed

None of these files exist. Path methods work on names only; Files methods touch the disk.

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?

Path anatomy, no disk needed Java 11+
Sign in to run this example in your browser.

Expected output

path:        projects/shop/src/Main.java
file name:   Main.java
parent:      projects/shop/src
root:        null
name count:  4
name(1):     shop
subpath:     shop/src
absolute?    false
resolve:     projects/shop/docs/readme.md
sibling:     projects/blog
normalize:   projects/shop/docs/readme.md
relativize:  ../blog/post.md
Path startsWith:   false
String startsWith: true
endsWith:    true