Library contents

Java File equality and ordering

Compare abstract pathnames and use them as map or set keys.

A simple example

File equality and ordering

  1. Start with Two paths both spelled a.txt
  2. Do this Compare the path values
  3. Result Equal
Identically formed path values compare equal. This comparison needs no file contents.

Syntax

Java syntax
public int compareTo(File pathname)
JDK 21 declarations (3)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Deduplicate receipt names before a download

A purchasing team receives the same invoice name from two forms. Use the pathname objects as keys while the files are still offline and verify why the duplicate occupies one set entry.

First output line0
Main.java
import java.nio.file.*;
import java.io.*;

class Main {
    public static void main(String[] args) throws Exception {
        File a = new File("receipts", "18.txt");
        File b = new File(new File("receipts"), "18.txt");
        System.out.println(a.compareTo(b));
        System.out.println(a.equals(b));
        System.out.println(a.hashCode() == b.hashCode());
    }
}
Output
0
true
true

These two constructions yield the same abstract pathname, so ordering and equality agree.

Advertisements

Keep two receipts with the same basename

Two shops both issue receipt number 18 and put their copies in separate folders. A catalog keyed by full path should retain both entries even though their filenames are identical.

First output linetrue
Main.java
import java.nio.file.*;
import java.io.*;

class Main {
    public static void main(String[] args) throws Exception {
        File north = new File("north", "18.txt");
        File south = new File("south", "18.txt");
        System.out.println(north.getName().equals(south.getName()));
        System.out.println(north.equals(south));
    }
}
Output
true
false

The filenames agree, but the parent components distinguish the two catalog keys.

Locate a rehearsal score

The choir stores each score inside a season folder. Two labels are built with the same parent and final name. Will their normalized path values compare equal?

Givenspring / alto.txt
Worked resultEqual

What to watch for

The comparison follows platform pathname rules. It does not establish that two different spellings reference the same disk entry.

Documentation for File equality and ordering