Java Class getResource() Method



Description

The Java Class getResource() finds a resource with a given name

Declaration

Following is the declaration for java.lang.Class.getResource() method

public URL getResource(String name)

Parameters

name − This is the name of the desired resource.

Return Value

This method returns a URL object or null if no resource with this name is found.

Exception

NA

Getting URL of a Non-Existing Resource Example

The following example shows the usage of java.lang.Class.getResource() method. In this program, we've created an instance of ClassDemo and then using getClass() method, the class of the instance is retrieved. Using getResource(), we've retrieved the url of a file and printed the same.

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

Output

Let us compile and run the above program, this will produce the following result −

Value = null
Value = null

Getting URL of a Existing Resource Example

The following example shows the usage of java.lang.Class.getResource() method. In this program, we've created an instance of ClassDemo and then using getClass() method, the class of the instance is retrieved. Using getResource(), we've retrieved the url of a file and printed the same. Here we've ensured that file.txt is present in the same package as the class.

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

Output

Let us compile and run the above program, this will produce the following result −

Value = file:/C:/Users/Tutorialspoint/eclipse-workspace/Tutorialspoint/bin/com/tutorialspoint/file.txt
java_lang_class.htm
Advertisements