Java Resource File getStreamFromResource(Class clazz, String resourceName)

Here you can find the source of getStreamFromResource(Class clazz, String resourceName)

Description

Get a string from a Resource .

License

Open Source License

Parameter

Parameter Description
clazz class to get classloader from (<code>null</code> to skip loading as classpath resource)
resourceName resource name

Exception

Parameter Description
IOException on any error loading

Return

resource stream

Declaration

public static InputStream getStreamFromResource(Class<?> clazz, String resourceName) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    /**//from  w w  w. ja v a 2  s.  co m
     * Get a string from a <i>Resource </i>. This can either be a URL, an absolute file name
     * or a relative file name. A special URL that has a scheme of <i>res</i> is also supported,
     * this gets the resource by name from the classloader that provided <code>clazz</code>.
     * 
     * @param clazz class to get classloader from (<code>null</code> to skip loading as classpath resource)
     * @param resourceName resource name
     * @return resource stream
     * @throws IOException 
     * @throws IOException on any error loading
     */
    public static InputStream getStreamFromResource(Class<?> clazz, String resourceName) throws IOException {

        // A resource name
        if (resourceName.startsWith("res://") && clazz != null) {
            URL url = clazz.getResource(resourceName.substring(6));
            if (url == null) {
                throw new FileNotFoundException("Resource " + resourceName + " not found on CLASSPATH.");
            }
            return url.openStream();
        } else {
            try {
                // A URL
                URL url = new URL(resourceName);
                return url.openStream();
            } catch (MalformedURLException murle) {
                File file = new File(resourceName);
                // A file
                return new FileInputStream(file);
            }
        }
    }
}

Related

  1. getLastModified(final String resourceName)
  2. getParentResource(final Class c, final String resource)
  3. getSampleDir(File resourcesDir)
  4. getShortName(String resource, Map nsMap)
  5. getSourceForResource(String s)
  6. getTestResourceFile(String pName, Class pClass)
  7. inputStream(Class baseClass, String resourceName)
  8. isFullIRI(String resource)
  9. loadAutoConfigFiles(ClassLoader classLoader, String resourceName)