Java Resource Path Get getResource(String path)

Here you can find the source of getResource(String path)

Description

Loads the resource from the class loader returned by #getClassLoader() .

License

Apache License

Parameter

Parameter Description
path The classpath of the resource.

Exception

Parameter Description
UsageException When the provided path does not translate to a valid resource.

Return

The URL of the resource identified by the provided path.

Declaration

public static URL getResource(String path) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.net.URL;

public class Main {
    /**//from  w  w w.  jav a  2  s.c om
     * Loads the resource from the class loader returned by {@link #getClassLoader()}.
     * 
     * @param path
     *            The classpath of the resource.
     * @return The URL of the resource identified by the provided path.
     * @throws UsageException
     *             When the provided path does not translate to a valid resource.
     * @see ClassLoader#getResource(java.lang.String)
     */
    public static URL getResource(String path) {
        URL url = getClassLoader().getResource(path);

        if (url == null)
            throw new IllegalArgumentException("Unable to find resource at " + path);

        return url;
    }

    /**
     * @return Returns the current thread's context class loader; when not found it returns the system class loader.
     */
    public static ClassLoader getClassLoader() {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();

        return loader == null ? ClassLoader.getSystemClassLoader() : loader;
    }

    /**
     * @return Returns the class loader of the provided class; when not found it returns the class loader from
     *         {@link #getClassLoader()}.
     */
    public static ClassLoader getClassLoader(Class<?> clazz) {
        ClassLoader loader = clazz.getClassLoader();

        return loader == null ? getClassLoader() : loader;
    }
}

Related

  1. getRelativeResource(Class clazz, String relativePath)
  2. getResource(Class cl, String path)
  3. getResource(final Class baseClass, final String path)
  4. getResource(final String path)
  5. getResource(String path)
  6. getResource(String relativePath)
  7. getResource(String resourcePath)
  8. getResourceAsFile(Object relativeTo, String relativePath)
  9. getResourceAsFile(String relativePath)