Example usage for java.lang Class getResourceAsStream

List of usage examples for java.lang Class getResourceAsStream

Introduction

In this page you can find the example usage for java.lang Class getResourceAsStream.

Prototype

@CallerSensitive
public InputStream getResourceAsStream(String name) 

Source Link

Document

Finds a resource with a given name.

Usage

From source file:com.bradmcevoy.io.FileUtils.java

@SuppressWarnings("unchecked")
public static String readResource(Class cl, String res) throws IOException {
    InputStream in = cl.getResourceAsStream(res);
    if (in == null) {
        throw new IOException(
                "Failed to read resource: " + res + " relative to class: " + cl.getCanonicalName());
    }/*  w  w  w.j  a  v  a2  s  .c o  m*/
    ByteArrayOutputStream out = readIn(in);
    return out.toString();
}

From source file:XMLUtilities.java

/**
 * Tries to find the given systemId in the context of the given
 * class. If the given systemId ends with the given test string,
 * then try to load a resource using the Class's
 * <code>getResourceAsStream()</code> method using the test string
 * as the resource.//ww  w . j a  va  2  s. com
 *
 * <p>This is used a lot internally while parsing XML files used
 * by jEdit, but anyone is free to use the method if it sounds
 * usable.</p>
 */
public static InputSource findEntity(String systemId, String test, Class where) {
    if (systemId != null && systemId.endsWith(test)) {
        try {
            return new InputSource(new BufferedInputStream(where.getResourceAsStream(test)));
        } catch (Exception e) {
        }
    }

    return null;
}

From source file:Log4jPropertyHelper.java

public static void updateLog4jConfiguration(Class<?> targetClass, String log4jPath) throws Exception {
    Properties customProperties = new Properties();
    FileInputStream fs = null;//from w  w w  .j  av  a 2s .co  m
    InputStream is = null;
    try {
        fs = new FileInputStream(log4jPath);
        is = targetClass.getResourceAsStream("/log4j.properties");
        customProperties.load(fs);
        Properties originalProperties = new Properties();
        originalProperties.load(is);
        for (Entry<Object, Object> entry : customProperties.entrySet()) {
            originalProperties.setProperty(entry.getKey().toString(), entry.getValue().toString());
        }
        LogManager.resetConfiguration();
        PropertyConfigurator.configure(originalProperties);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(fs);
    }
}

From source file:org.ow2.sirocco.cimi.server.resource.serialization.SerializationHelper.java

/**
 * Get a ressource in classpath and convert it as string.
 * //www  .j  ava 2  s .  c  o m
 * @param classLocation This class allows to find the package which is
 *        located the ressoure
 * @param resourceName The name of ressource
 * @param encoding The encoding name. If null the default encoding is used
 * @return The string with the content of ressource
 * @throws IOException In case of IO error
 */
public static String getResourceAsString(final Class<?> classLocation, final String resourceName,
        final String encoding) throws IOException {
    InputStream in = classLocation.getResourceAsStream(resourceName);
    if (null == in) {
        throw new IOException("Resource not found : " + resourceName);
    }
    return SerializationHelper.convertStreamToString(classLocation.getResourceAsStream(resourceName), encoding);
}

From source file:com.liferay.portal.search.elasticsearch.internal.util.ResourceUtil.java

public static File getResourceAsTempFile(Class<?> clazz, String name) throws IOException {

    int index = name.lastIndexOf(CharPool.PERIOD);

    File file = File.createTempFile(name.substring(0, index), name.substring(index));

    file.deleteOnExit();//from  w w w  .ja va 2  s.  com

    try (InputStream inputStream = clazz.getResourceAsStream(name)) {
        FileUtils.copyInputStreamToFile(inputStream, file);
    }

    return file;
}

From source file:org.artifactory.util.ResourceUtils.java

public static void copyResource(String resourcePath, OutputStream outputStream,
        InputStreamManipulator manipulator, Class clazz) throws IOException {
    InputStream origInputStream = null;
    InputStream usedInputStream = null;
    try {//from   ww w .j av a  2 s  .c  o  m
        origInputStream = clazz != null ? clazz.getResourceAsStream(resourcePath)
                : Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
        assertResourceNotNull(resourcePath, origInputStream);
        if (manipulator != null) {
            InputStream mip = manipulator.manipulate(origInputStream);
            if (mip == null) {
                throw new RuntimeException("Received a null stream from stream manipulation");
            }
            usedInputStream = mip;
        } else {
            usedInputStream = origInputStream;
        }
        IOUtils.copy(usedInputStream, outputStream);
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(usedInputStream);
        IOUtils.closeQuietly(origInputStream);
    }
}

From source file:name.martingeisse.api.i18n.ClassHierarchyLocalizationContext.java

/**
 * Loads the .properties file for the origin class and the specified locale and returns
 * either its contents as a map, or an empty map if the file cannot be found.
 * /*www.j av  a  2  s.c  o  m*/
 * This method is static to emphasize that it does not use or affect the calling instance
 * in any other way.
 * 
 * @param origin the origin class
 * @param locale the locale
 * @return the properties
 */
private static Map<String, String> loadProperties(Class<?> origin, Locale locale) {
    String filename = origin.getSimpleName() + '_' + locale + ".properties";
    try (InputStream inputStream = origin.getResourceAsStream(filename)) {
        if (inputStream == null) {
            @SuppressWarnings("unchecked")
            Map<String, String> emptyMap = MapUtils.EMPTY_MAP;
            return emptyMap;
        }
        Properties properties = new Properties();
        properties.load(inputStream);
        @SuppressWarnings("unchecked")
        Map<String, String> typedProperties = (Map<String, String>) (Map<?, ?>) properties;
        return typedProperties;
    } catch (IOException e) {
        logger.error("could not load i18n property file", e);
        return null;
    }
}

From source file:ja.centre.gui.resources.Resources.java

public static String asString(Class aClass, String suffix) {
    String name = aClass.getName();
    name = "/" + name.replace(".", "/") + suffix;
    InputStream is = aClass.getResourceAsStream(name);

    if (is == null) {
        Arguments.doThrow("Resource file file for class \"" + aClass.getName() + "\" does not exist");
    }//from w  w  w  . j a  v a2s  . co m

    StringBuilder builder = new StringBuilder();
    try {
        byte[] buffer = new byte[32768];
        int read;
        while ((read = is.read(buffer)) != -1) {
            builder.append(new String(buffer, 0, read, "UTF-8"));
        }
    } catch (IOException e) {
        States.shouldNeverReachHere(e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            LOG.error("Exception occured when tried to close html resource input stream", e);
        }
    }
    return builder.toString();
}

From source file:org.craftercms.commons.monitoring.VersionMonitor.java

/**
 * Gets the current VersionMonitor base on a Class that will load it's manifest file.
 * @param clazz Class that will load the manifest MF file
 * @return A {@link VersionMonitor} pojo with the information.
 * @throws IOException If Unable to read the Manifest file.
 *///from   www. j  a  va 2s.c  o m
public static VersionMonitor getVersion(Class clazz) throws IOException {
    Manifest manifest = new Manifest();
    manifest.read(clazz.getResourceAsStream(MANIFEST_PATH));
    return getVersion(manifest);
}

From source file:com.squarespace.template.GeneralUtils.java

/**
 * Loads a resource from the Java package relative to {@code cls}, raising a
 * CodeException if it fails.//from ww  w  . j  ava  2  s  . c o m
 */
public static String loadResource(Class<?> cls, String path) throws CodeException {
    try (InputStream stream = cls.getResourceAsStream(path)) {
        if (stream == null) {
            throw new CodeExecuteException(resourceLoadError(path, "not found"));
        }
        return IOUtils.toString(stream, "UTF-8");
    } catch (IOException e) {
        throw new CodeExecuteException(resourceLoadError(path, e.toString()));
    }
}