Java Resource Path Get getResourceAsString(String path)

Here you can find the source of getResourceAsString(String path)

Description

get Resource As String

License

Apache License

Declaration

public static final String getResourceAsString(String path) 

Method Source Code

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

import java.io.*;
import java.net.URL;

public class Main {
    public static final String getResourceAsString(String path) {
        try {/*  ww  w  . jav a 2s . c  o  m*/
            URL resource = Thread.currentThread().getContextClassLoader()
                    .getResource(path);
            if (resource != null) {
                return readFromStream(Thread.currentThread()
                        .getContextClassLoader().getResourceAsStream(path));
            } else {
                throw new RuntimeException(new FileNotFoundException(path));
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static final String readFromStream(final InputStream is) {
        if (is == null) {
            return "";
        }
        final char[] buffer = new char[1024];
        final StringBuilder out = new StringBuilder();
        try {
            final Reader in = new InputStreamReader(is, "UTF-8");
            try {
                for (;;) {
                    int rsz = in.read(buffer, 0, buffer.length);
                    if (rsz < 0)
                        break;
                    out.append(buffer, 0, rsz);
                }
            } finally {
                in.close();
            }
        } catch (UnsupportedEncodingException ex) {
            /* ... */
        } catch (IOException ex) {
            /* ... */
        }
        return out.toString();
    }
}

Related

  1. getResource(String resourcePath)
  2. getResourceAsFile(Object relativeTo, String relativePath)
  3. getResourceAsFile(String relativePath)
  4. getResourceAsStream(final String path)
  5. getResourceAsStream(String resourcePath, ClassLoader classLoader, Class clazz)
  6. getResourceFile(Class clazz, String relPath)
  7. getResourceFile(final Class baseClass, final String path)
  8. getResourceFile(String sResourcePath, Class cRefClass)
  9. getResourceFilePath(String name)