How to access a sub-file/folder in Java 7 java.nio.file.Path?

JavaPathNioJava 7

Java Problem Overview


Java 7 introduced java.nio.file.Path as a possible replacement for java.io.File.

With File, when I access a file under a specific, I would do:

File parent = new File("c:\\tmp");
File child = new File(parent, "child"); // this accesses c:\tmp\child

What's the way to do this with Path?

I supposed this will work:

Path parent = Paths.get("c:\\tmp");
Path child = Paths.get(parent.toString(), "child");

But calling parent.toString() seems ugly. Is there a better way?

Java Solutions


Solution 1 - Java

Use the resolve method on Path.

There are two methods with this name. One takes a relative Path and the other a String. It uses the Path on which it is called as a parent and appends the String or relative Path appropriately.

Path parent = Paths.get("c:\\tmp");
Path child = parent.resolve("child");

Solution 2 - Java

To anyone finding this question looking specifically only for files that are within the specified path, you must be aware of path traversal attacks.

See: https://stackoverflow.com/questions/33083397/filtering-upwards-path-traversal-in-java-or-scala/33084369#33084369

It is critical that you check that the path starts with the root.

Path parent = Paths.get("C:\\tmp");
Path child = parent.resolve("chlid").normalize();
if (!child.startsWith(parent)) {
    throw new IllegalArgumentException("Potential Path Traversal Attack");
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionripper234View Question on Stackoverflow
Solution 1 - JavaErick RobertsonView Answer on Stackoverflow
Solution 2 - JavaRyan LeachView Answer on Stackoverflow