Java file equals


 

Java file equals

This section illustrates you the use of method equals() of File class.

This section illustrates you the use of method equals() of File class.

Java file equals

This section illustrates you the use of method equals() of File class.

Description of code:

Here we are going to check the equality of two file class objects using equals() method. This method checks whether the pathname of two file objects are same or not and returns boolean value. It returns false, if the path of both the files are not equal. You can see in the given example, we have specified two text files of same name but different path. In this case, it matches both the file instances and will return false as the path of both the files are different. No matter of having the same file name.

equals() method: This method of File class checks whether the pathname are equal or not. 

Here is the code:

import java.io.*;

public class FileEquals {
	public static void main(String args[]) {
		File file1 = new File("C:/java/filename.txt");
		File file2 = new File("c:/examples/filename.txt");
		System.out.println("File 1: " + file1);
		System.out.println("File 2: " + file2);
		boolean b = file1.equals(file2);
		System.out.println("IS filenames are equal?: " + b);
	}
}

Through the method equals(), you can check the equality of two file objects.

Output:

File 1: c:\java\filename.txt
File 2: c:\example\filename.txt
IS filenames are equal?: false

Ads