java.io.File getCanonicalPath()

Description

On this document we will be showing a java example on how to use the getCanonicalPath() method of File Class. This method Returns the canonical pathname string of this abstract pathname.

Notes:

  • A canonical pathname is both absolute and unique. The precise definition of canonical form is system-dependent. This method first converts this pathname to absolute form if necessary, as if by invoking the getAbsolutePath() method, and then maps it to its unique form in a system-dependent way. This typically involves removing redundant names such as “.” and “..” from the pathname, resolving symbolic links (on UNIX platforms), and converting drive letters to a standard case (on Microsoft Windows platforms).
  • Every pathname that denotes an existing file or directory has a unique canonical form. Every pathname that denotes a nonexistent file or directory also has a unique canonical form. The canonical form of the pathname of a nonexistent file or directory may be different from the canonical form of the same pathname after the file or directory is created. Similarly, the canonical form of the pathname of an existing file or directory may be different from the canonical form of the same pathname after the file or directory is deleted

Throws:

  • IOException – If an I/O error occurs, which is possible because the construction of the canonical pathname may require filesystem queries
  • SecurityException – If a required system property value cannot be accessed, or if a security manager exists and its SecurityManager.checkRead(java.io.FileDescriptor) method denies read access to the file

Method Syntax

public String getCanonicalPath()
throws IOException

Method Argument

Data Type Parameter Description
N/A N/A N/A

Method Returns

This method returns the canonical pathname string denoting the same file or directory as this abstract pathname.

Compatibility

Requires Java 1.1 and up

Java File getCanonicalPath() Example

Below is a java code┬ádemonstrates the use of getCanonicalPath()┬ámethod of File class. The example presented might be simple however it shows the behaviour of the getCanonicalPath()┬ámethod of File class.┬áBasically we have put a check first if the file exists or not. If the file exists based on the return value of the exists() method, we print the result of the┬ágetCanonicalPath() method to illustrate it’s behaviour.

Sample Output

Below is the sample output when you run the above example.

java lang File getCanonicalPath() example output

Suggested Reading List

References