Java -Get path of a file

Posted on November 5, 2016


The java.io.File 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.

FilePathExample.java

package com.boraji.tutorial.io;

import java.io.File;
import java.io.IOException;

/**
 * @author imssbora
 * FilePathExample.java
 * Nov 5, 2016
 */
public class FilePathExample {
	public static void main(String[] args) throws IOException {
		File file=new File("../../file.txt");
		System.out.println();
		
		if(file.exists()){
			/*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);
		}else{
			System.out.println("File does not exist");
		}
	}
}

Output

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