Package ca.pgon.st.light

Source Code of ca.pgon.st.light.ResourceTools

/*
    Small Tools - Some basic libraries for developing and testing http://www.pgon.ca/st
    Copyright (C) 2013 Small Tools (info@pgon.ca)

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
package ca.pgon.st.light;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import ca.pgon.st.light.exception.StLightException;

/**
* Some common methods to manage resources files.
*
* @author Simon Levesque
*
*/
public final class ResourceTools {

    private static final int BUFFER_SIZE = 1024;

    private ResourceTools() {
    }

    /**
     * Load a resource as a String.
     *
     * @param resource
     *            the resource to open as an absolute path
     * @return the string
     */
    public static String getResourceAsString(String resource) {
        return getResourceAsString(resource, ResourceTools.class);
    }

    /**
     * Load a resource as a String.
     *
     * @param resource
     *            the resource to open
     * @param context
     *            the context class to use relative path
     * @return the string
     */
    public static String getResourceAsString(String resource, Class<?> context) {
        InputStream in = null;
        try {
            in = context.getResourceAsStream(resource);
            Reader reader = new InputStreamReader(in);
            StringBuilder sb = new StringBuilder();

            char[] chars = new char[BUFFER_SIZE];
            int len;
            while ((len = reader.read(chars)) != -1) {
                sb.append(chars, 0, len);
            }
            return sb.toString();
        } catch (Exception e) {
            throw new StLightException("Cannot load resource", e);
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }
}
TOP

Related Classes of ca.pgon.st.light.ResourceTools

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.