Java Utililty Methods Resource Load

List of utility methods to do Resource Load

Description

The list of methods to do Resource Load are organized into topic(s).

Method

InputStreamgetResourceAsStream(String resourcePath)
We must get the Resource as a stream from the ContextClassLoader and not from the normal classLoader acquired by using getClass.getClassLoader, since we must be able to load resources from different threads e.g.
return Thread.currentThread().getContextClassLoader().getClass().getResourceAsStream(resourcePath);
InputStreamgetResourceAsStreamInClassPath(@SuppressWarnings("rawtypes") Class clazz, String filepath)
get Resource As Stream In Class Path
return clazz.getClassLoader().getResourceAsStream(filepath);
InputStreamgetResourceAsStrem(String name)
get Resource As Strem
return Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
StringgetResourceAsString(Class clazz, String name)
get Resource As String
return getString(clazz.getResourceAsStream(name));
StringgetResourceAsString(Class clazz, String resource)
Retrieves a Resource as a String if exists, else returns null
InputStream stream = clazz.getResourceAsStream(resource);
if (stream == null)
    return null;
return toString(stream);
StringgetResourceAsString(Class theClass, String fileName)
get Resource As String
File f = new File(theClass.getResource(fileName).getFile());
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
    sb.append(line + "\n");
    line = br.readLine();
...
StringgetResourceAsString(final String resourceName, final Class caller, final String charset)
get Resource As String
return new String(readStream(getResourceAsStream(resourceName, caller)), charset);
StringgetResourceAsString(InputStream in)
get Resource As String
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
byte[] buf = new byte[1024];
int sz = 0;
try {
    while (true) {
        sz = in.read(buf);
        baos.write(buf, 0, sz);
        if (sz < buf.length)
...
StringgetResourceAsString(InputStream resource)
get Resource As String
BufferedReader br = new BufferedReader(new InputStreamReader(resource));
StringBuilder sb = new StringBuilder();
int c;
while ((c = br.read()) != -1) {
    sb.append((char) c);
br.close();
return sb.toString();
...
StringgetResourceAsString(String name)
get Resource As String
InputStream is = getResource(name);
Scanner scanner = new Scanner(is, "UTF-8");
StringBuilder sb = new StringBuilder();
while (scanner.hasNext()) {
    sb.append(scanner.nextLine()).append("\n");
return sb.toString();