Open In App

URL sameFile() method in Java with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

The sameFile() function of Java.net.URL class is used to compare two URLs excluding the fragment part. This method returns true if both the URL are same excluding the fragment part else returns false.

Function Signature

public boolean sameFile(URL u)

Syntax

url1.sameFile(url2);

Parameter: This method accepts a mandatory parameter url which is the second url to be compared to this url.

Return Value: This method returns true if both the URL are same excluding the fragment part else returns false.

Below methods illustrate URL.sameFile() method:

Example 1:




// Java program to illustrate
// URL.sameFile() method
  
import java.net.*;
  
class GFG {
    public static void main(String args[]) throws Exception
    {
  
        // create URL1
        URL url1
            = new URL("https:// www.geeksforgeeks.org");
  
        // create URL2
        URL url2
            = new URL("https:// www.geeksforgeeks.org");
  
        // check if two URL are same or not
        System.out.print("URL 1 is compared to URL 2: ");
  
        if (url1.sameFile(url2))
            System.out.println("same");
        else
            System.out.println("not same");
    }
}


Output:

URL 1 is compared to URL 2: same

Example 2: The sameFile() function has a specific use that makes it different from the equals() function. The sameFile() function compares the URL excluding the fragment part. The following example will illustrate the use which makes it different from equals function.




// Java program to check the use of sameFile
  
import java.net.*;
  
class GFG {
    public static void main(String args[]) throws Exception
    {
        // create URL1
        URL url1
            = new URL("https:// www.geeksforgeeks.org");
  
        // create URL2
        URL url2
            = new URL("https:// www.geeksforgeeks.org#print");
  
        // check if two URL are same or not
        System.out.print("URL 1 is compared to URL 2: ");
  
        if (url1.sameFile(url2))
            System.out.println("same");
        else
            System.out.println("not same");
    }
}


Output:

URL 1 is compared to URL 2: same

Note: If equals function would have been used, then the second code would have printed “not same” but using the sameFile() function it will give result “same”.



Last Updated : 10 May, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads