Java Path File Read nio openResourceReader(Class resourceOrigin, String resourcePath)

Here you can find the source of openResourceReader(Class resourceOrigin, String resourcePath)

Description

Creates a reader for reading the specified class loader resource.

License

Apache License

Parameter

Parameter Description
resourceOrigin the class which the specified resource path is relative to.
resourcePath the resource path, relative to the specified reference class.

Exception

Parameter Description
IOException if the specified resource is not found, or another I/O error occurs.

Return

the reader.

Declaration

static Reader openResourceReader(Class<?> resourceOrigin, String resourcePath) throws IOException 

Method Source Code

//package com.java2s;
/*//from w  ww.j  a v  a2  s .co 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.
 */

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 {
    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

  1. loadTitles(Path rootDir, Set container)
  2. newBufferedReader(Path path)
  3. newBufferedReader(Path path)
  4. openBufferedReader(String pathOrUrl)
  5. openForReadingAndWriting(String filePath)
  6. read(String aPathString)
  7. read(String filePath)
  8. read(String filePath)
  9. read(String path)