Java.io.File.getCanonicalPath() Method
Advertisements
Description
The java.io.File.getCanonicalPath() method returns the canonical pathname string of this abstract pathname. This method removes redundant names such as "." and ".." from the pathname
Declaration
Following is the declaration for java.io.File.getCanonicalPath() method:
public String getCanonicalPath()
Parameters
NA
Return Value
The method returns the canonical pathname string
Exception
IOException -- if an I/O error occurs
SecurityException -- if a system property value can not be accessed.
Example
The following example shows the usage of java.io.File.getCanonicalPath() method.
package com.tutorialspoint;
import java.io.File;
public class FileDemo {
public static void main(String[] args) {
File f = null;
String path = "";
boolean bool = false;
try{
// create new files
f = new File("C:\\Program Files\\..\\test.txt");
// create new canonical form file object
path = f.getCanonicalPath();
// if the file path exists
bool = f.exists();
// if file exists
if(bool)
{
// prints
System.out.print(path+" Exists? "+ bool);
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}
}
}
Let us compile and run the above program, this will produce the following result:
C:\test.txt Exists? true