Concatenating Path

In Java 7 a new file api was introduced. This new file api is represented by the java.nio package. With the old api java.io it was possible to concatenate two file/folder easily. Let’s have a look how this works with the java.nio.file.Path

With java.io.File it was possible to use

new File(new File(new File("absolute"),"relative"),"file");

A concatenation like that is not apparently available in java.nio.file.Path. But when having a look at it there is a method called resolve. Using Path.resolve it is possible to concatenate different paths.

// in case there are different paths available that must be concatenated
Path relative = Paths.get("relative");
Path file = Paths.get("file");
Paths.get("absolute").resolve(relative).resolve(file);

// much easier in case there are not paths available
Paths.get("absolute", "relative","file");

// bad practice
Paths.get("absolute/relative/file");

Sources

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.