Java File equals() method with examples

January 04, 2020 No comments Java IO Examples File equals

1. Introduction

The equals() method tests if the given pathname is equal to that provided in the argument. This method returns true if the argument is not null and is pointing to the same file or directory. Equality depends upon the underlying operating system. Note that on UNIX systems, the alphabetic case is significant in comparing pathnames; on Microsoft Windows systems it is not.

2. Method signature

public boolean equals(Object obj)

Parameters:

  • obj - object that should be compared with given File instance

Returns

  • true - if the objects are the same

3. Examples

3.1. The program presents several comparisons on File objects

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 dir = new File("/tmp");

            System.out.println(file.equals(dir)); // false

            System.out.println(file.equals(new File("/tmp/frontbackend.txt"))); // true

            System.out.println(file.equals(new File("frontbackend.txt"))); // false

            System.out.println(dir.equals("/tmp")); // false

            System.out.println(file.equals(null)); // false

            System.out.println(dir.equals(new File("/tmp"))); // true

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

The output:

false
true
false
false
false
true

4. Conclusion

In this article we presented File.equals() method available in Java IO API. The method checks if two File instance is equal. Note that this method does not compare the content of the file or directory, it is only checked if pathnames are the same.

{{ message }}

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