Monday, January 16, 2012

Java 7: Path API in Java NIO 2

The Path class is introduced in Java 7 which is an upgraded version of the well-known class.

Before Java 7:


File file = new File("abc.xml");

With Java 7:

import java.nio.file.Path;
import java.nio.file.Paths;

Path path = Paths.get("abc.xml");

Usages of Path API

Constructing a Path Between Two Locations

When you need to construct a path from one location to another, you can call the relativize() method, which constructs a relative path between this path and a given path. This method constructs a path originating from the original path and ending at the location specified by the passed-in path. The new path is relative to the original path.

Path path1 = Paths.get("abc.txt");
Path path2 = Paths.get("xyz.txt");

In this case, it is assumed that abc.txt and xyz.txt are siblings, which means that you can
navigate from one to the other by going up one level and then down one level.

Path path1_to_path2 = path1.relativize(path2);

Output: ..\xyz.txt

Comparing Two Paths

The equality of two Paths can be tested in different ways for different purposes. You can test whether two paths are equal by calling the Path.equals() method. It does not access the file system, so the compared paths are not required to exist, and it does not check if the paths are the same file.

Path path1 = Paths.get("/books/java/bitterjava.pdf");
Path path2 = Paths.get("C://books/java/bitterjava.pdf");
    System.out.println("The paths are equal!");
} else {
    System.out.println("The paths are not equal!"); //true

Iterate over the Name Elements of a Path

You can iterate either by using an explicit iterator or with a foreach loop that returns a Path object for each iteration.

Path path = Paths.get("C:", "books/java", "bitterjava.pdf");
for (Path bookname : path) {

No comments: