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:/Windows/System32 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.io;

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

Leave a Reply

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