Java 教程

Java 控制語句

面向物件程式設計

Java 內建類

Java 檔案處理

Java 錯誤與異常

Java 多執行緒

Java 同步

Java 網路程式設計

Java 集合

Java 介面

Java 資料結構

Java 集合演算法

高階 Java

Java 雜項

Java API 與框架

Java 類參考

Java 有用資源

Java - URL getFile() 方法及示例



描述

Java URL getFile() 方法返回此 URL 的檔名。返回的檔案部分將與 getPath() 相同,加上 getQuery() 的值(如果存在)。如果沒有查詢部分,則此方法和 getPath() 將返回相同的結果。

宣告

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

public String getFile()

引數

返回值

此 URL 的檔名,如果不存在則為空字串。

異常

示例 1

以下示例演示了使用 Java URL getFile() 方法處理使用 https 協議的有效 url。在這個示例中,我們建立了一個 URL 類的例項。現在使用 getFile() 方法,我們獲取檔名並列印它。

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","www.tutorialspoint.com","/index.htm");
         String content = url.getFile();
         System.out.println(content);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

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

輸出

/index.htm

示例 2

以下示例演示了使用 Java URL getFile() 方法處理帶有查詢引數的有效 url。在這個示例中,我們建立了一個 URL 類的例項。現在使用 getFile() 方法,我們獲取檔名並列印它。

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");
         String fileName = url.getFile();
         System.out.println(fileName);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

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

輸出

/index.htm?language=en

示例 3

以下示例演示了使用 Java URL getFile() 方法處理使用檔案協議的有效 url。在這個示例中,我們建立了一個 URL 類的例項。現在使用 getFile() 方法,我們獲取檔名並列印它。

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("file","www.tutorialspoint.com","/index.htm");
         String fileName = url.getFile();
         System.out.println(fileName);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

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

輸出

/index.htm
java_url.htm
廣告