How do I create a java.nio.Path?

The following code snippet show you how to create a Path. A Path (java.nio.Path) in an interface that represent a location in a file system, such as C:WindowsSystem32 or /usr/bin.

To create a Path we can use the java.nio.Paths.get(String first, String... more) methods. Below you can see how to create a Path by passing only the first string and by passing a first string plus some varargs string.

package org.kodejava.example.nio;

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


public class PathCreate {
    public static void main(String[] args) {
        //
        // Create a Path that represents Windows installation
        // location.
        //
        Path windows = Paths.get("C:\Windows");
        //
        // Check to see if the path represent a directory.
        //
        if (Files.isDirectory(windows)) {
            // do something
        }

        //
        // Create a Path that represent Windows programs installation
        // location.
        //
        Path programFiles = Paths.get("C:\Program Files");
        Files.isDirectory(programFiles);

        //
        // Create a Path that represent the notepad.exe program
        //
        Path notepad = Paths.get("C:\Windows", "System32", "notepad.exe");
        // Check to see if the path represent an executable file.
        if (Files.isExecutable(notepad)) {
            // do something
        }
    }
}

Wayan Saryada

I am a programmer, a runner, an open water diver and currently living in the island of Bali, Indonesia. If you need help on Java programming you can hire me on Fiverr.

Leave a Comment.