Java Resource Load getResourceAsString(Class clazz, String resource)

Here you can find the source of getResourceAsString(Class clazz, String resource)

Description

Retrieves a Resource as a String if exists, else returns null

License

Open Source License

Parameter

Parameter Description
resource resource name

Return

resource as string

Declaration

public static String getResourceAsString(Class<?> clazz, String resource) 

Method Source Code


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

import java.io.*;

public class Main {
    /**/*from   w w w .j a  v a2 s . c  om*/
     * Retrieves a Resource as a String if exists, else returns null
     *
     * @param resource resource name
     * @return resource as string
     */
    public static String getResourceAsString(Class<?> clazz, String resource) {
        InputStream stream = clazz.getResourceAsStream(resource);
        if (stream == null)
            return null;
        return toString(stream);
    }

    public static String toString(InputStream stream) {
        BufferedReader reader = createBufferedReader(stream);
        StringWriter writer = new StringWriter();
        int b;
        try {
            while ((b = reader.read()) != -1) {
                writer.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return writer.toString();
    }

    public static BufferedReader createBufferedReader(InputStream stream) {
        return new BufferedReader(new InputStreamReader(stream));
    }
}

Related

  1. getResourceAsStream(String resource, ClassLoader classLoader)
  2. getResourceAsStream(String resourcePath)
  3. getResourceAsStreamInClassPath(@SuppressWarnings("rawtypes") Class clazz, String filepath)
  4. getResourceAsStrem(String name)
  5. getResourceAsString(Class clazz, String name)
  6. getResourceAsString(Class theClass, String fileName)
  7. getResourceAsString(final String resourceName, final Class caller, final String charset)
  8. getResourceAsString(InputStream in)
  9. getResourceAsString(InputStream resource)