Java File getAbsolutePath() method with examples

January 04, 2020 No comments Java IO Examples File getAbsolutePath

1. Introduction

The getAbsolutePath() method returns the absolute path of the given file or directory. The method is system-dependent. On Windows OS a relative path is made absolute by resolving ti against the current folder of the drive named by the pathname. On UNIX a relative path is made absolute by resolving the current user directory.

2. Method signature

public String getAbsolutePath()

Parameters:

  • method does not take any parameter

Returns

  • String - the absolute pathname of the given file or directory

Throws

  • SecurityException - if a required system property value cannot be accessed.

3. Examples

3.1. Program that prints several absolute paths using getAbsolutePath() method

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

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

            System.out.println(file.getAbsolutePath()); 
            System.out.println(test.getAbsolutePath());
            System.out.println(txt.getAbsolutePath()); 
            System.out.println(tmp.getAbsolutePath()); 
            System.out.println(empty.getAbsolutePath()); 

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

When the .java file was runned under /home/frontbackend/projects/tutorials directory we will have the following output:

/home/frontbackend/projects/tutorials/frontbackend.txt
/home/frontbackend/projects/tutorials/../frontbackend/test
/home/frontbackend/projects/tutorials/./frontbackend.txt
/tmp
/home/frontbackend/projects/tutorials/./../tmp/./frontbackend/..

4. Conclusion

In this article, we showcased the File.getAbsolutePath() method that returns the absolute path of the specified file or directory. Keep in mind that this method works differently on Windows and Unix OS.

{{ message }}

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