Java Resource Get getResourceAsStream(String resourceLocation)

Here you can find the source of getResourceAsStream(String resourceLocation)

Description

Resolve the given resource string to a java.io.InputStream.

License

LGPL

Parameter

Parameter Description
resourceLocation eg, "classpath:config/log4j.default", "file:///C:/reinier.reg"

Exception

Parameter Description
IOException an exception

Return

a corresponding InputStream object

Declaration

public static InputStream getResourceAsStream(String resourceLocation) throws IOException 

Method Source Code

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

import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;

import java.net.MalformedURLException;

import java.net.URL;

public class Main {
    /** Pseudo URL prefix for loading from the class path: "classpath:" */
    public static final String CLASSPATH_URL_PREFIX = "classpath:";

    /**/*w w  w. j  ava  2 s.  co m*/
     * Resolve the given resource string to a <code>java.io.InputStream</code>.
     * Search from classpath(in jar or outside of jar) or from filesystem
     * 
     * @param resourceLocation
     *            eg, "classpath:config/log4j.default", "file:///C:/reinier.reg"
     * @return a corresponding InputStream object
     * @throws IOException
     */
    public static InputStream getResourceAsStream(String resourceLocation) throws IOException {
        if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
            String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
            return Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
        }
        try {
            // try URL
            return new URL(resourceLocation).openStream();
        } catch (MalformedURLException ex) {
            // no URL -> treat as file path
            return new FileInputStream(resourceLocation);
        }

    }
}

Related

  1. getResourceAsFile(final Class clazz, final String name)
  2. getResourceAsFile(final String filename, final Class theClass)
  3. getResourceAsFile(String name)
  4. getResourceAsStream(Class aClass, String name)
  5. getResourceAsStream(final Class caller, final String resource)
  6. getResourceAsString(String prefix, String resource)
  7. getResourceAsString(String resource)
  8. getResourceBase()
  9. getResourceBundleLocaleString(String sKey, Object[] sParam, String sResourceBundle)