Java File getCanonicalFile() method with examples

January 04, 2020 No comments Java IO Examples File getCanonicalFile

1. Introduction

The getCanonicalFile() method returns the canonical form of the file or directory. Equivalent to new File(file.getCanonicalPath()) method.

2. Method signature

public File getCanonicalFile() throws IOException

Parameters:

  • method does not take any parameter

Returns

  • File - the canonical pathname of the specified file or directory

Throws

  • IOException - in case an I/O error occurs
  • SecurityException - when we do not have access to the file or directory

3. Examples

3.1. Program that compares getCanonicalFile() and getAbsoluteFile() 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 files");
            System.out.println(file.getCanonicalFile()); // /tmp/frontbackend.txt
            System.out.println(test.getCanonicalFile()); // /tmp/frontbackend/test
            System.out.println(txt.getCanonicalFile()); // /tmp/frontbackend/frontbackend.txt
            System.out.println(tmp.getCanonicalFile()); // /tmp
            System.out.println(empty.getCanonicalFile()); // /tmp

            System.out.println();

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

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

The output:

Canonical files
/tmp/frontbackend.txt
/tmp/frontbackend/test
/tmp/frontbackend/frontbackend.txt
/tmp
/tmp

Absolute files
/tmp/frontbackend.txt
/tmp/frontbackend/../frontbackend/test
/tmp/frontbackend/./frontbackend.txt
/tmp
/./../tmp/./frontbackend/..

4. Conclusion

In this article, we presented File.getCanonicalFile() method that can be used to get the canonical representation of the file or directory. This method is behavior is similar to getCanonicalPath() with the difference in the result object.

{{ message }}

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