131. Joining file paths

Joining (or combining) file paths means defining a fixed root path and appending to it a partial path or replacing a part of it (for example, a filename needs to be replaced with another filename). Basically, this is a handy technique when we want to create new paths that share a common fixed part.

This can be accomplished via NIO.2 and the Path.resolve() and Path.resolveSibling() methods.

Let's consider the following fixed root path:

Path base = Paths.get("D:/learning/packt");

Let's also assume that we want to obtain the Path for two different books:

// D:learningpacktJBossTools3.pdf
Path path = base.resolve("JBossTools3.pdf");

// D:learningpacktMasteringJSF22.pdf
Path path = base.resolve("MasteringJSF22.pdf");

We can use this feature to loop a set of files; for example, let's loop a String[] of books:

Path basePath = Paths.get("D:/learning/packt");
String[] books = {
"Book1.pdf", "Book2.pdf", "Book3.pdf"
};

for (String book: books) {
Path nextBook = basePath.resolve(book);
System.out.println(nextBook);
}

Sometimes, the fixed root path contains the filename as well:

Path base = Paths.get("D:/learning/packt/JavaModernChallenge.pdf");

This time, we can replace the name of the file (JavaModernChallenge.pdf) with another name via the resolveSibling() method. This method resolves the given path against this path's parent path, as shown in the following example:

// D:learningpacktMasteringJSF22.pdf
Path path = base.resolveSibling("MasteringJSF22.pdf");

If we bring the Path.getParent() method into the discussion and we chain the resolve() and resolveSibling() methods, then we can create more complex paths, as shown in the following example:

// D:learningpublisherMyBook.pdf
Path path = base.getParent().resolveSibling("publisher")
.resolve("MyBook.pdf");

The resolve()/resolveSibling() method comes in two flavors – resolve​(String other) / resolveSibling​(String other) and resolve​(Path other) / resolveSibling​(Path other), respectively.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset