Java 教程

Java 控制語句

面向物件程式設計

Java 內建類

Java 檔案處理

Java 錯誤和異常

Java 多執行緒

Java 同步

Java 網路程式設計

Java 集合

Java 介面

Java 資料結構

Java 集合演算法

高階 Java

Java 其他

Java API 和框架

Java 類引用

Java 有用資源

Java - URL sameFile(URL other) 方法及示例



描述

Java URL sameFile(URL other) 方法比較兩個 URL,不包括片段元件。如果此 URL 和另一個引數在不考慮片段元件的情況下相等,則返回 true。

宣告

以下是 java.net.sameFile(URL other) 方法的宣告

Compares two URLs, excluding the fragment component.

引數

other − 要比較的 URL。

返回值

如果它們引用相同的遠端物件,則返回 true;否則返回 false。

異常

示例 1

以下示例演示了 Java URL sameFile(URL e) 方法的用法。在此示例中,我們建立了兩個具有相同 url 的 URL 類的例項。現在使用 sameFile() 方法比較這兩個物件。由於物件基於相同的 url,結果與預期一致,並在輸出中得到驗證,如下所示:

package com.tutorialspoint;

import java.io.IOException;
import java.net.URL;

public class UrlDemo {
   public static void main(String [] args) {
      try {
         URL url = new URL("https://tutorialspoint.tw/index.htm?language=en#j2se");
         URL urlToCompare = new URL("https://tutorialspoint.tw/index.htm?language=en#j2se");
         System.out.println(url.sameFile(urlToCompare));
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

讓我們編譯並執行上述程式,這將產生以下結果:

輸出

true

示例 2

以下示例演示了 Java URL sameFile(URL e) 方法的用法。在此示例中,我們建立了兩個具有相同 url 但片段不同的 URL 類的例項。現在使用 sameFile() 方法比較這兩個物件。由於物件基於相同的 url,結果與預期一致,並在輸出中得到驗證,如下所示:

package com.tutorialspoint;

import java.io.IOException;
import java.net.URL;

public class UrlDemo {
   public static void main(String [] args) {
      try {
         URL url = new URL("https://tutorialspoint.tw/index.htm?language=en#j2se");
         URL urlToCompare = new URL("https://tutorialspoint.tw/index.htm?language=en");
         System.out.println(url.sameFile(urlToCompare));
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

讓我們編譯並執行上述程式,這將產生以下結果:

輸出

true

示例 3

以下示例演示了 Java URL equals(Object e) 方法的用法。在此示例中,我們建立了兩個具有相同 url 的 URL 類的例項,在另一個例項中,我們還傳遞了主機和檔名。現在使用 sameFile 方法比較這兩個物件。由於物件現在不同,結果與預期一致,並在輸出中得到驗證,如下所示:

package com.tutorialspoint;

import java.io.IOException;
import java.net.URL;

public class UrlDemo {
   public static void main(String [] args) {
      try {
         URL url = new URL("https://tutorialspoint.tw/index.htm?language=en#j2se");
         URL urlToCompare = new URL("https", "https://tutorialspoint.tw","index.htm?language=en#j2se" );
         System.out.println(url.sameFile(urlToCompare));
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

讓我們編譯並執行上述程式,這將產生以下結果:

輸出

false
java_url.htm
廣告
© . All rights reserved.