Java Class getResource() 方法



描述

Java Class getResource() 方法用於查詢具有給定名稱的資源。

宣告

以下是 java.lang.Class.getResource() 方法的宣告:

public URL getResource(String name)

引數

name − 這是所需資源的名稱。

返回值

此方法返回一個 URL 物件,如果找不到具有此名稱的資源,則返回 null。

異常

獲取不存在的資源的 URL 示例

以下示例演示了 java.lang.Class.getResource() 方法的用法。在這個程式中,我們建立了一個 ClassDemo 的例項,然後使用 getClass() 方法獲取該例項的類。使用 getResource(),我們檢索了檔案的 URL 並打印出來。

package com.tutorialspoint;

import java.net.URL;

public class ClassDemo {

   public static void main(String[] args) throws Exception {
   
      ClassDemo c = new ClassDemo();
      Class cls = c.getClass();

      // finds resource relative to the class location
      URL url = cls.getResource("file.txt");
      System.out.println("Value = " + url);
   }
}

輸出

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

Value = null
Value = null

獲取存在的資源的 URL 示例

以下示例演示了 java.lang.Class.getResource() 方法的用法。在這個程式中,我們建立了一個 ClassDemo 的例項,然後使用 getClass() 方法獲取該例項的類。使用 getResource(),我們檢索了檔案的 URL 並打印出來。這裡我們確保 file.txt 與類位於同一個包中。

package com.tutorialspoint;

import java.io.File;
import java.net.URL;

public class ClassDemo {

   public static void main(String[] args) throws Exception {
      File file = new File("file.txt");
      ClassDemo c = new ClassDemo();
      Class cls = c.getClass();

      // finds resource relative to the class location
      URL url = cls.getResource("file.txt");
      System.out.println("Value = " + url);
   }
}

輸出

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

Value = file:/C:/Users/Tutorialspoint/eclipse-workspace/Tutorialspoint/bin/com/tutorialspoint/file.txt
java_lang_class.htm
廣告
© . All rights reserved.