Java Language Retrieving information about a path


Example

Information about a path can be get using the methods of a Path object:

  • toString() returns the string representation of the path

    Path p1 = Paths.get("/var/www"); // p1.toString() returns "/var/www"
    
  • getFileName() returns the file name (or, more specifically, the last element of the path

    Path p1 = Paths.get("/var/www"); // p1.getFileName() returns "www"
    Path p3 = Paths.get("C:\\Users\\DentAr\\Documents\\HHGTDG.odt"); // p3.getFileName() returns "HHGTDG.odt"
    
  • getNameCount() returns the number of elements that form the path

    Path p1 = Paths.get("/var/www"); // p1.getNameCount() returns 2
    
  • getName(int index) returns the element at the given index

    Path p1 = Paths.get("/var/www"); // p1.getName(0) returns "var", p1.getName(1) returns "www"
    
  • getParent() returns the path of the parent directory

    Path p1 = Paths.get("/var/www"); // p1.getParent().toString() returns "/var"
    
  • getRoot() returns the root of the path

    Path p1 = Paths.get("/var/www"); // p1.getRoot().toString() returns "/"
    Path p3 = Paths.get("C:\\Users\\DentAr\\Documents\\HHGTDG.odt"); // p3.getRoot().toString() returns "C:\\"