集册 Java实例教程 返回具有指定绝对名称的资源的输入流。

返回具有指定绝对名称的资源的输入流。

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

682
返回具有指定绝对名称的资源的输入流。

/*

 * Copyright (c) 2015-2016 QuartzDesk.com.

 * Licensed under the MIT license (https://opensource.org/licenses/MIT).

 */

//package com.nowjava;

import java.io.BufferedInputStream;/**时 代 J a v a - nowjava.com**/

import java.io.IOException;

import java.io.InputStream;


public class Main {

    public static void main(String[] argv) throws Exception {

        String absoluteName = "nowjava.com";

        System.out.println(getResourceAsStream(absoluteName));

    }


    /**

     * Returns the input stream for the resource with the specified absolute name.

     * The resource is loaded through the current thread's context class loader.

     *

     * @param absoluteName a resource name.

     * @return the resource input stream.

     * @throws IOException if the resource was not found.

     */

    public static InputStream getResourceAsStream(String absoluteName)

            throws IOException {

        String resourceName = absoluteName.startsWith("/") ? absoluteName

                .substring(1) : absoluteName;

        InputStream ins = Thread.currentThread().getContextClassLoader()

                .getResourceAsStream(resourceName);


        if (ins == null)/* from 时 代 J a v a*/

            throw new IOException("Cannot find resource: " + absoluteName);


        return new BufferedInputStream(ins);

    }


    /**

     * Returns the input stream for the resource with the specified relative name.

     * The name is treated as relative and the package name of the specified

     * class is prepended to that name to make the name absolute. The resource

     * is loaded through the current thread's context class loader.

     *

     * @param relativeName a resource name (relative, or absolute).

     * @param clazz a class used to make the resource name absolute and load the resource.

     * @return the resource input stream.

     * @throws IOException if the resource was not found.

     */

    public static InputStream getResourceAsStream(String relativeName,

            Class<?> clazz) throws IOException {

        String newName = getAbsoluteResourceName(relativeName, clazz);

        return getResourceAsStream(newName);

    }


    
展开阅读全文