Java URI sameFile()方法及示例

来源:这里教程网 时间:2026-02-17 21:16:06 作者:

Java URI sameFile()方法及示例

Java.net.URL类的 sameFile() 函数被用来比较两个URL,不包括片段部分。如果两个URL都是相同的,不包括片段部分,该方法返回真,否则返回假。

函数签名

public boolean sameFile(URL u)

语法

url1.sameFile(url2);

参数。该方法接受一个强制性参数url,这是第二个要和这个url比较的url。

返回值。如果两个URL都是相同的,不包括片段部分,这个方法返回真,否则返回假。

下面的方法说明了URL.sameFile()方法。

例子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");    }}

输出:

URL 1 is compared to URL 2: same

例2: sameFile()函数有一个特殊的用途,使它与equals()函数不同。sameFile()函数比较的是不包括片段部分的URL。下面的例子将说明它与 equals 函数不同的用途。

// 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");    }}

输出:

URL 1 is compared to URL 2: same

注意: 如果使用equals函数,那么第二段代码将打印出 “不相同”,但使用sameFile()函数,将得到 “相同 “的结果。

相关推荐