Determining if two Filename paths refer to the same file.

This program is going to determine that the file name refers to the same file or not.

Determining if two Filename paths refer to the same file.

This program is going to determine that the file name refers to the same file or not.

Determining if two Filename paths refer to the same file.

Determining if two Filename paths refer to the same file.

     

This program is going to determine that the file name refers to the same file or not. What you need to do is to create two File object and pass the file name in the constructor of both the File class. Now match both the file instances. It will return false if the file paths are not equal. To send the true value we first have to normalize both the paths, only after that  it will return true. 

In this program we have used following methods: 

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

getCanonicalFile():
It denotes the same file or directory its abstract pathname. It throws IOException and SecurityException.

Code of the program is given below:

import java.io.*;

public class FileNameReferToSameFile{
public static void main(String args[]){
File file1 = new File("./filename.txt");
File file2 = new File("filename.txt");
System.out.println("Actual fileName1 = " + file1 + "\n");
System.out.println("Actual fileName2 = " + file2 + "\n");

// It returns false if Filename paths are not equal 
boolean b = file1.equals(file2); 
System.out.println("It checks whether the file name 

paths are equal or not" + b);



// Normalize the paths
try {
file1 = file1.getCanonicalFile(); // c:\tapan\filename
file2 = file2.getCanonicalFile(); // c:\tapan\filename
System.out.println("Actual path of filName1 = " + file1 + "\n");
System.out.println("Actual path of fileName2 = " + file2 + "\n");
} catch (IOException e) {
System.out.println("IOException is "+ e);
}

// It returns true if Filename paths are equal
b = file1.equals(file2); 
System.out.println("the file name are now equal" + b);
System.out.println("Actual path of fileName1 = " + file1 + "\n");
System.out.println("Actual path of fileName2 = " + file2 + "\n");
}
} 

Output of this program is given below:

C:\FileNameReferToSameFile>java FileNameReferToSameFile
Actual Filename1 = .\FileNameReferToSameFile.txt

Actual Filename2 = FileNameReferToSameFile.txt

It checks whether the file name are equal or notfalse
Actual Filename1 = C:\FileNameReferToSameFile\FileNameReferToSameFile.txt

Actual Filename2 = C:\FileNameReferToSameFile\FileNameReferToSameFile.txt

the file name are now equaltrue
Actual Filename1 = C:\FileNameReferToSameFile\FileNameReferToSameFile.txt

Actual Filename2 = C:\FileNameReferToSameFile\FileNameReferToSameFile.txt

Download this example: