Java.lang.Class.getResource() Method

Advertisements


Description

The java.lang.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

Example

The following example shows the usage of java.lang.Class.getResource() method.

package com.tutorialspoint;

import java.net.URL;
import java.lang.*;

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

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

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

Value = file:/C:/Program%20Files/Java/jdk1.6.0_06/bin/file.txt
Value = null



Advertisements
Advertisements