Java NIO2 – Path, Paths and Files
In this article we are going to see java.nio package – Path, Paths and Files.
First let us understand these terms,
Path – This is an interface which replaces File
Paths – This contains methods to create path object
Files – Contains methods that work with Path object
Similar to files, We can perform operations like creating, deleting, moving and copying operations using Path too. We are going to see an example about how to create, copy, move and delete a file using Path.
Creating Path:
Path path = Paths.get(“directory”);
After using the above to create a directory, then we have to create the directory – Note that similar to files, Path just creates an object and does not create the directory/file. We have to declare createDirectory/createFile to create the directory or file.
Now let us see an example,
public class filenio2 { public static void main(String[] args) throws IOException { Path path = Paths.get("F:/JavaInfiniteFolder"); // creating an path object Path filecreate = Paths.get("F:/JavaInfiniteFolder/test.txt"); // creating path object Path cfile = Paths.get("F:/JavaCopied"); // creating path object Files.createDirectory(path); // creating a directory --> JavainfiniteFolder Files.createDirectory(cfile); // creating the directory --> JavaCopied Files.createFile(filecreate); // creating test.txt file System.out.println("Created"); Files.copy(path, cfile, StandardCopyOption.REPLACE_EXISTING); // copying from javainfinitefolder to javacopied Files.move(path, cfile, StandardCopyOption.REPLACE_EXISTING); // moving from javainfinitefolder to javacopied Files.createDirectories(path); // Recreating since it is moved Files.createFile(filecreate); // Recreating since it is moved System.out.println("Copied"); Files.delete(filecreate); // deleting the text.txt Files.delete(path); // deleting the directory System.out.println("Deleted"); } }