ADMFactory
Tutorials from a developer perspective

File Path, Absolute Path and Canonical Path in Java

by ADM

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

Example

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

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