Java -Get path of a file

Posted on November 5, 2016

The class provides the following methods for getting the path of a file.

  • getPath()- This method return the string which denote the path that is used to create the associate File object.
  • getAbsolutePath() - This method returns the path string after resolving it against the current directory if it's relative, resulting in a fully qualified path.
  • getCanonicalPath() – This method returns the path string after resolving any relative path against current directory, and removes any relative path element e.g. (. and ..).

Here is an example to demonstrate this.



 * @author imssbora
 * Nov 5, 2016
public class FilePathExample {
	public static void main(String[] args) throws IOException {
		File file=new File("../../file.txt");
			/*Get path*/
			String path=file.getPath();
			System.out.println("Path is : "+path);
			/*Get absolute path*/
			String absolutePath=file.getAbsolutePath();
			System.out.println("Absolute path is : "+absolutePath);
			/*Get canonical path*/
			String canonicalPath=file.getCanonicalPath();
			System.out.println("Canonical path is : "+canonicalPath);
			System.out.println("File does not exist");


Path is : ..\..\file.txt
Absolute path is : D:\Work\Workspace\boraji.tutorial\..\..\file.txt
Canonical path is : D:\Work\file.txt