File getCanonicalPath() method in Java with Examples
The getCanonicalPath() method is a part of Path class. This function returns the Canonical pathname of the given file object. If the pathname of the file object is Canonical then it simply returns the path of the current file object. The Canonical path is always absolute and unique, the function removes the ‘.’ ‘..’ from the path, if present.
For Example: if we create a file object using the path as “program.txt”, it points to the file present in the same directory where the executable program is kept (if you are using an IDE it will point to the file where you have saved the program ). Here the path of the file mentioned above is “program.txt” but this path is not absolute (i.e. not complete). The function getCanonicalPath() will return a path which will be an absolute and unique path from the root directories. The canonical form of an existing file may be different from the canonical form of a same non existing file and the canonical form of an existing file may be different from the canonical form of the same file when it is deleted.
public String getCanonicalPath()
Parameters: This function does not accept any parameters.
Return value: The function returns a String value if the Canonical Path of the given File object.
Exception: This method throws following exceptions:
Below programs will illustrate the use of getAbsolutePath() method:
Example 1: We have a File object with a specified path we will try to find its canonical path.
Original file path : c:\program Canonical file path : C:\program
Example 2: We have a File object with a specified path we will try to find its canonical path .
Original file path : c:\users\..\program Canonical file path : C:\program
The programs might not run in an online IDE. please use an offline IDE and set the path of the file
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.