Java File getCanonicalPath() method with examples

January 04, 2020 No comments Java IO Examples File getCanonicalPath

1. Introduction

The getCanonicalPath() method returns the canonical path of the given file or directory. The precise definition of this method is system-dependent. The method first uses the absolute form of the path and then removes all redundant names such as . and .. from the pathname. It is better to explain a real-life example of how this method works with comparison to getAbsolutePath().

2. Method signature

public String getCanonicalPath() throws IOException

Parameters:

  • method does not take any parameter

Returns

  • String - the canonical pathname string of the specified file or directory

Throws

  • IOException - if an I/O error occurs
  • SecurityException - if a required system property value cannot be accessed

3. Examples

3.1. Program that compares getCanonicalPath() and getAbsolutePath() methods

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File file = new File("/tmp/frontbackend.txt");
            File test = new File("/tmp/frontbackend/../frontbackend/test");
            File txt = new File("/tmp/frontbackend/./frontbackend.txt");
            File tmp = new File("/tmp");
            File empty = new File("/./../tmp/./frontbackend/..");

            System.out.println("Canonical paths");
            System.out.println(file.getCanonicalPath()); // /tmp/frontbackend.txt
            System.out.println(test.getCanonicalPath()); // /tmp/frontbackend/test
            System.out.println(txt.getCanonicalPath()); // /tmp/frontbackend/frontbackend.txt
            System.out.println(tmp.getCanonicalPath()); // /tmp
            System.out.println(empty.getCanonicalPath()); // /tmp

            System.out.println();

            System.out.println("Absolute paths");
            System.out.println(file.getAbsolutePath()); // /tmp/frontbackend.txt
            System.out.println(test.getAbsolutePath()); // /tmp/frontbackend/../frontbackend/test
            System.out.println(txt.getAbsolutePath()); // /tmp/frontbackend/./frontbackend.txt
            System.out.println(tmp.getAbsolutePath()); // /tmp
            System.out.println(empty.getAbsolutePath()); // /./../tmp/./frontbackend/..

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

Canonical paths
/tmp/frontbackend.txt
/tmp/frontbackend/test
/tmp/frontbackend/frontbackend.txt
/tmp
/tmp

Absolute paths
/tmp/frontbackend.txt
/tmp/frontbackend/../frontbackend/test
/tmp/frontbackend/./frontbackend.txt
/tmp
/./../tmp/./frontbackend/..

4. Conclusion

In this article, we presented getCanonicalPath() method that can be used to get the unique form of the file or directory. Note that this method works differently on UNIX and Windows OS.

{{ message }}

{{ 'Comments are closed.' | trans }}