Creates a reader for reading the specified class loader resource. - Java Reflection

Java examples for Reflection:Class Loader

Description

Creates a reader for reading the specified class loader resource.

Demo Code

/*/*from   www.  jav  a2 s.c  o m*/
 * Copyright 2013 Anton Karmanov
 *
 * 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 com.java2s;

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

import java.io.Reader;
import java.nio.charset.Charset;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class resourceOrigin = String.class;
        String resourcePath = "java2s.com";
        System.out
                .println(openResourceReader(resourceOrigin, resourcePath));
    }

    private static final Charset CHARSET = Charset.forName("UTF-8");

    /**
     * Creates a reader for reading the specified class loader resource.
     * 
     * @param resourceOrigin the class which the specified resource path is relative to.
     * @param resourcePath the resource path, relative to the specified reference class.  
     * @return the reader.
     * @throws IOException if the specified resource is not found, or another I/O error occurs.
     */
    static Reader openResourceReader(Class<?> resourceOrigin,
            String resourcePath) throws IOException {
        InputStream in = resourceOrigin.getResourceAsStream(resourcePath);
        if (in == null) {
            throw new FileNotFoundException("File not found: "
                    + resourcePath);
        }
        try {
            Reader reader = new InputStreamReader(in, CHARSET);
            in = null;
            return reader;
        } finally {
            if (in != null) {
                //Close the input stream only if Reader construction failed.
                in.close();
            }
        }
    }
}

Related Tutorials