Java Language New File I/O Retrieving information about a path

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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:\\"
    


Got any Java Language Question?