Java Resource Load getResourceAsString(final String resourceName, final Class caller, final String charset)

Here you can find the source of getResourceAsString(final String resourceName, final Class caller, final String charset)

Description

get Resource As String

License

Open Source License

Declaration

public static String getResourceAsString(final String resourceName, final Class<?> caller, final String charset)
            throws IOException 

Method Source Code


//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    public static String getResourceAsString(final String resourceName, final Class<?> caller, final String charset)
            throws IOException {
        return new String(readStream(getResourceAsStream(resourceName, caller)), charset);
    }//  w w w.j a  va 2 s.co  m

    public static byte[] readStream(final InputStream is) throws IOException {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final byte[] buffer = new byte[256];
        while (true) {
            final int count = is.read(buffer);
            if (count <= 0) {
                break;
            }
            baos.write(buffer, 0, count);
        }
        return baos.toByteArray();
    }

    public static InputStream getResourceAsStream(final String resourceName, final Class<?> caller) {
        final String resource;
        if (resourceName.startsWith("/")) {
            resource = resourceName.substring(1);
        } else {
            final Package callerPackage = caller.getPackage();
            if (callerPackage != null) {
                resource = callerPackage.getName().replace('.', '/') + '/' + resourceName;
            } else {
                resource = resourceName;
            }
        }
        final ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
        if (threadClassLoader != null) {
            final InputStream is = threadClassLoader.getResourceAsStream(resource);
            if (is != null) {
                return is;
            }
        }

        final ClassLoader classLoader = caller.getClassLoader();
        if (classLoader != null) {
            final InputStream is = classLoader.getResourceAsStream(resource);
            if (is != null) {
                return is;
            }
        }

        return ClassLoader.getSystemResourceAsStream(resource);
    }
}

Related

  1. getResourceAsStreamInClassPath(@SuppressWarnings("rawtypes") Class clazz, String filepath)
  2. getResourceAsStrem(String name)
  3. getResourceAsString(Class clazz, String name)
  4. getResourceAsString(Class clazz, String resource)
  5. getResourceAsString(Class theClass, String fileName)
  6. getResourceAsString(InputStream in)
  7. getResourceAsString(InputStream resource)
  8. getResourceAsString(String name)
  9. getResourceAsString(String path)