Java - File System - Path

About

File System - Path in Java.

The path is unique identifier of a file (directory)

Management

Instantiation

In nio, a Path instance represents a file or directory but doesn't access the file system (for instance in order to verify that a particular Path exists)

Path myPath1 = Paths.get("C:\\temp1\\temp2");
// Is Equivalent to
// Path myPath2 = FileSystems.getDefault().getPath("C:\\temp1\\temp2\\temp3");

Meta Information retrieval

  • from a nio path object:
System.out.println("The Name File is: "+myPath1.getFileName());
System.out.println("The number of element in the path is: "+myPath1.getNameCount());
System.out.println("The path of the parent directory is: "+myPath1.getParent());
System.out.println("The root is: "+myPath1.getRoot());
System.out.println("");
System.out.println("Index retrieval: First element in the path is: "+myPath1.getName(0));
System.out.println("Slice retrieval: Subpath from 0 until 2 is : "+myPath1.subpath(0,2));
The Name File is: temp2
The number of element in the path is: 2
The path of the parent directory is: C:\temp1
The root is: C:\

Index retrieval: First element in the path is: temp1
Slice retrieval: Subpath from 0 until 2 is : temp1\temp2

Separator

Path

The path separator used in any search path variable

System.out.println(System.getProperty("path.separator"));
; # Output on windows

File

System.out.println(System.getProperty("file.separator"));
\ # Output on windows

Relativize / Resolve

To relativize a path, you use the relativize function

Path relativePath = basePath.relativize(absolutePath);

The inverse is called resolve

Path absolutePath = basePath.resolve(relativePath);

Powered by ComboStrap