Home » Core Java » nio » file » Path » java.nio.file.Path Example

About Prasad Saya

Prasad Saya
Prasad Saya is a software engineer with over ten years’ experience in application development, maintenance, testing and consulting on various platforms. He is a certified Java and Java EE developer. At present his interest is in developing Java applications. He also has experience working with databases and ERP applications.

java.nio.file.Path Example

This article introduces the Path interface and its basic usage. The Path interface is available in the Java SE 7 as part of Java NIO 2 File API. This article shows creating, getting information, converting and comparing paths.  The examples in this article are compiled and run in Windows OS environment.

Note that Java SE 7 is required to run the code in this example.

1. About

The Path interface is defined in the java.nio.file package, and this extends Comparable<Path>, Iterable<Path> and Watchable interfaces.

The Path is a programmatic representation of a path in the file system. A Path object contains the file or directory name, and directory used to construct the path. Path is used to examine, locate, and manipulate files. A root component, that identifies a file system hierarchy, may also be present. That means : Path = Root element + Name element(s) -or- Root element -or- Name element(s) separated by delimiters. The path delimiters are “\” for Windows and “/” for unix operating systems.


  • Path interface methods are sometimes called syntactic operations; because they operate on the path itself and do not access the file system, with the exception of one method: toRealPath().
  • Path objects are immutable, like String objects.

2. Creating a Path

The java.nio.file.Paths class’s get() static method is used to create a Path. This method converts a path string, or a sequence of  strings that when joined form a path string, to a Path.

Path path = Paths.get(String first, String... more); the method throws runtime InvalidPathException, if String contains illegal characters.

For example, in unix Path is created as follows:

Path p1 = Paths.get("/tmp/foo");
Path p2 = Paths.get("/foo","bar","gus");

The separator is “/”, and the path string “/foo/bar/gus” is converted to a Path.

In Windows environment use “\\” (separator + escape character). For example:

Path p3 = Paths.get("D:\\dir\\file.txt");
Path p4 = Paths.get("file.txt");

A Path can be created as an absolute or relative. In the above code snippet, p3 is an example of absolute path and p4 is a relative path.

The following example creates a Path in Windows OS. Note that a real file file1.txt does not exist in the file system.

Note the same example PathExample1.java file is used through out this article. In the following sections, the file is extended to show the code that belongs to the section’s topic.


import java.nio.file.Path;
import java.nio.file.Paths;
public class PathExample1 {
    private Path path; // instance variable
    public static void main (String [] args) {
        PathExample1 example = new PathExample1();
    private void createPath() {
        path = Paths.get("X:\\JCG\\articles\\Path\\file1.txt");
        System.out.println("Path created: " + path.toString());

The output is:

Path created: X:\JCG\articles\Path\file1.txt

In Windows if the separator (“\”) is used without an escape character there will be a compiler error: illegal escape character. The separator needs to use a backslash before the separator character to overcome this error. Also, note that the output shows only single backslashes.


  • Paths can also be used with URIs – this is not shown in this article.
  • The following method can also be used to get a path: Path p5 = FileSystems.getDefault().getPath("D:\\examples\\Path);

3. Retrieving information about a Path

Path stores the name elements as a sequence. The highest element in the structure is located at index 0. The lowest element is at index [n-1], where n is the number of name elements in the Path. There are methods for retrieving individual elements or a sub-sequence of the Path using these indexes.

The following code snippet shows some methods for retrieving the Path info.

Path path = Paths.get("/home/joe/examples"); // creates absolute path (NOTE: this is unix file system)
Path path = path.getFileName(); // returns Path examples
Path path = path.getName(0); // returns home
int count = path.getNameCount(); // returns 3 (home, joe and examples)
Path path = path.subpath(0, 2); // returns home/joe
Path path = path.getParent(); // returns /home/joe
Path path = path.getRoot(); // returns /; on Windows the output shows the drive, like "D:\"

Note the path.getRoot() method returns null, for a relative path.

The following code snippet shows example of retrieving the Path info. Note the same Java source file from the previous section is used.


public static void main (String [] args) {
    PathExample1 example = new PathExample1();
private void getPathInfo() {
    Path filename = path.getFileName();
    System.out.println("Filename: " + filename);
    Path name0 = path.getName(0);
    System.out.println("Name 0: " + name0);
    Path sub = path.subpath(0, 2);
    System.out.println("Sub path: " + sub);

The output is:

Path created: X:\JCG\articles\Path\file1.txt
Filename: file1.txt
Name 0: JCG
Sub path: JCG\articles

From the output:

  • file1.txt is the file name.
  • JCG is the highest element (index 0), before the root element.
  • JCG\articles is the sub path starting from index 0 and ending with index 2. The output path includes the starting element and the ending index-1 element; in this case 0 and 1 index elements.

NOTE: There is an iterator() method that returns a java.util.Iterator. The iterator is used, to iterate over the name elements (not the root element) for this path. The first element is the closest to the root.

4. Converting a Path

A Path can be converted:

  • from a relative path to an absolute path
  • to create a real path
  • to a java.io.File object and vice-versa

The following are the example code showing the path conversion. Note the same Java source file from the previous section is used.

4.1. Convert relative path to an absolute path


public static void main (String [] args) {
    PathExample1 example = new PathExample1();
private void convertPaths() {
    Path relative = Paths.get("file2.txt");
    System.out.println("Relative path: " + relative);
    Path absolute = relative.toAbsolutePath();
    System.out.println("Absolute path: " + absolute);

The output is:

Relative path: file2.txt
Absolute path: X:\JCG\articles\Path\file2.txt

Note the relative path is the path relative to the directory this program is run from; that is the X:\JCG\articles\Path directory.

4.2. Create a real path object

The toRealPath() method returns the real path of an existing file. Note that a real file is required in the file system, otherwise there will be an exception: java.nio.file.NoSuchFileException, a subclass of java.io.IOException. The method throws IOException.

private void convertPaths() {
    Path real = null;
    path = Paths.get("X:\\JCG\\articles\\Path\\realfile.txt");
    try {
        real = path.toRealPath();
    catch (IOException e) {
        System.out.println("Real path could not be created !");
    System.out.println("Real path: " + real);

The output is:

Real path: X:\JCG\articles\Path\realfile.txt

NOTE: Add the import statement for the java.io.IOException to the source code file.

4.3. Convert Path to File and File to Path objects

  • The toFile() method of Path interface returns a java.io.File object representing this path.
  • The toPath() method of File class returns a Path object constructed from the path.

5. Comparing two Paths

The equals() method of Path interface tests this path for equality for the given object. The following code snippet shows the usage of this method. Note the same Java source file from the previous section is used.


public static void main (String [] args) {
    PathExample1 example = new PathExample1();
private void comparePaths() {
    Path path2 = Paths.get("X:\\JCG\\articles\\Path2\\file1.txt");
    boolean equal = path2.equals(path);
    System.out.println("Paths equal? " + equal);

The output is:

Paths equal? false

The values of path and path2 variables are X:\\JCG\\articles\\Path\\file1.txt and X:\\JCG\\articles\\Path2\\file1.txt respectively. They are not equal, and hence a false result.

NOTE: There are two more methods to compare paths: startsWith() and endsWith(). These methods test if a path starts or ends with a supplied path. The methods return a boolean.

6. Download Java Source Code

This was an example of java.nio.file.Path.

You can download the source code of this example here: PathExample1.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments