集册 Java实例教程 创建一个读取器,以读取指定的类加载器资源。

创建一个读取器,以读取指定的类加载器资源。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

527
创建一个读取器,以读取指定的类加载器资源。

/*

 * 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.

 *///时代Java - N o w  J a v a . c o m 提供

//package com.nowjava;


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 {/**来自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m**/

        Class resourceOrigin = String.class;

        String resourcePath = "nowjava.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)
展开阅读全文