Java 教程

Java 控制語句

面向物件程式設計

Java 內建類

Java 檔案處理

Java 錯誤和異常

Java 多執行緒

Java 同步

Java 網路程式設計

Java 集合

Java 介面

Java 資料結構

Java 集合演算法

高階 Java

Java 雜項

Java API 和框架

Java 類引用

Java 有用資源

Java – URL 的 getPath() 方法及示例



描述

Java 的 URL getPath() 方法返回此 URL 的路徑部分。

宣告

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

public String getPath()

引數

返回值

此 URL 的路徑部分,如果不存在則為空字串。

異常

示例 1

以下示例演示了對具有 https 協議的有效 url 使用 Java URL getPath() 方法。在此示例中,我們正在建立 URL 類的例項。現在使用 getPath() 方法,我們獲取路徑並列印它。

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 path = url.getPath();
         System.out.println(path);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

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

輸出

/index.htm

示例 2

以下示例演示了對具有查詢引數的有效 url 使用 Java URL getPath() 方法。在此示例中,我們正在建立 URL 類的例項。現在使用 getPath() 方法,我們獲取路徑並列印它。

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 path = url.getPath();
         System.out.println(path);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

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

輸出

/index.htm

示例 3

以下示例演示了對具有檔案協議的有效 url 使用 Java URL getPath() 方法。在此示例中,我們正在建立 URL 類的例項。現在使用 getPath() 方法,我們獲取路徑並列印它。

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 path = url.getPath();
         System.out.println(path);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

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

輸出

/index.htm
java_url.htm
廣告
© . All rights reserved.