Java Class Path Load loadTextFromClassPath(Class cls, String filename)

Here you can find the source of loadTextFromClassPath(Class cls, String filename)

Description

load Text From Class Path

License

Open Source License

Declaration

public static final StringBuilder loadTextFromClassPath(Class<?> cls, String filename) 

Method Source Code

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

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main {
    public static final StringBuilder loadTextFromClassPath(Class<?> cls, String filename) {
        InputStream input = cls.getResourceAsStream(filename);
        if (input == null)
            return null;

        try {/*from   w  ww.  j  a  v a 2 s  .  co m*/
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuilder sb = new StringBuilder(Math.max(1, input.available()));
            String s;

            while ((s = in.readLine()) != null)
                sb.append(s).append('\n');
            in.close();
            input.close();
            return sb;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * Load the text from the classpath, the 'filename' have in the form of aaa/bbb/ccc.ext
     */
    public static final StringBuilder loadTextFromClassPath(String filename) {
        InputStream input = ClassLoader.getSystemResourceAsStream(filename);
        if (input == null)
            return null;

        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuilder sb = new StringBuilder(Math.max(1, input.available()));
            String s;

            while ((s = in.readLine()) != null)
                sb.append(s).append('\n');
            in.close();
            input.close();
            return sb;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}