Java ClassPath Get getClasspathResource(String path)

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

Description

get Classpath Resource

License

Apache License

Declaration

public static InputStream getClasspathResource(String path) throws IllegalArgumentException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.InputStream;

import java.net.MalformedURLException;
import java.net.URL;

public class Main {

    public static InputStream getClasspathResource(String path) throws IllegalArgumentException {
        if (path == null) {
            throw new IllegalArgumentException("the parameter 'path' is required.");
        }/*from   w  w w  .  j  av a2  s.  c om*/
        URL url = getClasspathResourceURL(path);

        if (url == null) {
            throw new IllegalArgumentException("the resource path[" + path + "] could not be found.");
        }

        InputStream inStream;
        try {
            inStream = url.openStream();
        } catch (Throwable e) {
            throw new IllegalArgumentException("It failed to get the resource[" + url + "].", e);
        }
        return inStream;
    }

    public static URL getClasspathResourceURL(String path) {
        if (path == null) {
            throw new IllegalArgumentException("the parameter 'path' is required.");
        }
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        return loader.getResource(path);
    }

    public static InputStream getResource(String url) throws IllegalArgumentException {
        URL resourceURL = getResourceURL(url);
        try {
            return resourceURL.openStream();
        } catch (Throwable e) {
            throw new IllegalArgumentException("resource open failed. url = [" + url + "].", e);
        }
    }

    public static URL getResourceURL(String url) {
        if (url == null) {
            throw new IllegalArgumentException("the parameter 'url' is required.");
        }
        if (url.startsWith("classpath:")) {
            return getClasspathResourceURL(url.substring("classpath:".length()));
        }
        try {
            return new URL(url);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException(String.format("illegal url was specified. path=[%s]", url), e);
        }
    }
}

Related

  1. getClasspathForClass(Class targetClass)
  2. getClassPathFromString(String classpath)
  3. getClassPathPath()
  4. getClasspathResource(final String resource)
  5. getClasspathResource(String name)
  6. getClasspathResourceAsFile(String resourceName)
  7. getClassPathResourcesAsStreams(String relativeResourceName)
  8. getClassPathRoot(Class cl)
  9. getClasspathString()