Java File isAbsolute() method with examples

April 28, 2020 No comments Java IO Examples File isAbsolute

1. Introduction

The isAbsolute() method test if given pathname is absolute. This function is system dependent. On Windows a pathname is absolute if its prefix is a drive specifier followed by \\ on UNIX systems, a pathname is absolute if its prefix is a /.

2. Method signature

public boolean isAbsolute()

Parameters:

  • method does not take any parameter

Returns

  • true - if this abstract pathname is absolute, false otherwise

3. Examples

3.1. Program that tests several absolute paths using isAbsolute() method

package com.frontbackend.java.io;

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.printf("%s - %s%n", "frontbackend.txt", file.isAbsolute()); // false
            System.out.printf("%s - %s%n", "../frontbackend/test", test.isAbsolute()); // false
            System.out.printf("%s - %s%n", "./frontbackend.txt", txt.isAbsolute()); // false
            System.out.printf("%s - %s%n", "/tmp", tmp.isAbsolute()); // true
            System.out.printf("%s - %s%n", "./../tmp/./frontbackend/..", empty.isAbsolute()); // false

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

output:

frontbackend.txt - false
../frontbackend/test - false
./frontbackend.txt - false
/tmp - true
./../tmp/./frontbackend/.. - false

4. Conclusion

In this article, we presented isAbsolute() method from Java File API. Keep in mind that this method works differently on Windows and UNIX systems, which should understandable considering the different approaches to file storage.

{{ message }}

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