File Path, Absolute Path and Canonical Path in Java

  • 22 May 2017
  • ADM

 

File Path, Absolute Path and Canonical Path in Java - images/logos/java.jpg

 

java.io.File class contains three methods for determining the file path.

  • getPath(): This method returns the abstract pathname as pathname String.
  • getAbsolutePath(): This method returns the absolute path of the file, if File is created with an absolute pathname, this path will be returned. If file object is created using the relative path, the absolute pathname is resolved in a system-dependent way.
  • getCanonicalPath(): this method returns the canonical pathname string

Example

here is an example of using all three methods in 2 cases:

  • The file object is created using an absolute path.
  • The file object is created using a relative path.
package com.admfactory.io;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class JavaPathExample {

    public static void main(String[] args) throws IOException, URISyntaxException {
	System.out.println("File Path, Absolute Path and Canonical Path Example");
	System.out.println();
	/** file created using absolute path */
	File file = new File("C:\\Users\\admfactory\\file1.txt");
	printPaths(file);

	/** file created using relative path */
	file = new File("file2.txt");
	printPaths(file);

	/** file created using complex relative */
	file = new File("C:\\Users\\admfactory\\..\\examples\\file3.txt");
	printPaths(file);

	/** file created using URI */
	file = new File(new URI("file:///C:/Users/admfactory/file4.txt"));
	printPaths(file);
    }

    private static void printPaths(File file) throws IOException {
	System.out.println("Absolute Path: " + file.getAbsolutePath());
	System.out.println("Canonical Path: " + file.getCanonicalPath());
	System.out.println("Path: " + file.getPath());
	System.out.println();
    }
}

Output

Here is the output of the example.

File Path, Absolute Path and Canonical Path Example

Absolute Path: C:\Users\admfactory\file1.txt
Canonical Path: C:\Users\admfactory\file1.txt
Path: C:\Users\admfactory\file1.txt

Absolute Path: D:\Repositories\Bitbucket\admfactory.com\JavaIO\file2.txt
Canonical Path: D:\Repositories\Bitbucket\admfactory.com\JavaIO\file2.txt
Path: file2.txt

Absolute Path: C:\Users\admfactory\..\examples\file3.txt
Canonical Path: C:\Users\examples\file3.txt
Path: C:\Users\admfactory\..\examples\file3.txt

Absolute Path: C:\Users\admfactory\file4.txt
Canonical Path: C:\Users\admfactory\file4.txt
Path: C:\Users\admfactory\file4.txt

 

References