How to Create Java NIO Path?

Category: Java   Tags: Java, Java File Handling, Java Path, Java NIO File System

A Path object can be created by using one of the following get methods from the Paths:

                                Path path1 = Paths.get("/test/dir");
                                Path path2 = Paths.get(URI.create("file:///Users/mydir/test.txt"));
                                Path path3 = Paths.get(myDir);
                              

Here is a simple Java program that shows how Path works:

JavaPathExample.java

                            package com.tutorial.java.files;

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

                            public class JavaPathExample {

                                public static void main(String[] args) throws IOException {
                                    Path path1 = Paths.get("//home//test//sample.txt");
                                    System.out.println("Parent: " + path1.getParent());
                                    System.out.println("Root: " + path1.getRoot());
                                    System.out.println("Parent: " + path1.getParent());
                                    System.out.println("FileName: " + path1.getFileName());
                                    System.out.println("Number of element in path: " + path1.getNameCount());
                                    Path path2 = Paths.get("//home//test//sample.txt");
                                    System.out.println("path1 == path2: " + path1.equals(path2));
                                }
                            }
                        

Output:

                            Parent: /home/test
                            Root: /
                            Parent: /home/test
                            FileName: sample.txt
                            Number of element in path: 3
                            path1 == path2: true