Java.lang.ClassLoader.getResourceAsStream() 方法

描述

java.lang.ClassLoader.getResourceAsStream() 方法返回一个用于读取指定资源的输入流。


声明

以下是 java.lang.ClassLoader.getResourceAsStream() 方法的声明。

public InputStream getResourceAsStream(String name)

参数

name − 这是资源名称。


返回值

此方法返回用于读取资源的输入流,如果找不到资源,则返回 null。


异常

NA


示例

下面的例子展示了 java.lang.ClassLoader.getResourceAsStream() 方法的使用。

package com.tutorialspoint;

import java.lang.*;
import java.io.*;

class ClassLoaderDemo {

   static String getResource(String rsc) {
      String val = "";

      try {
         Class cls = Class.forName("ClassLoaderDemo");

         // returns the ClassLoader object associated with this Class
         ClassLoader cLoader = cls.getClassLoader();
         
         // input stream
         InputStream i = cLoader.getResourceAsStream(rsc);
         BufferedReader r = new BufferedReader(new InputStreamReader(i));

         // reads each line
         String l;
         while((l = r.readLine()) != null) {
            val = val + l;
         } 
         i.close();
      } catch(Exception e) {
         System.out.println(e);
      }
      return val;
   }
    
   public static void main(String[] args) {

     System.out.println("File1: " + getResource("file.txt"));
     System.out.println("File2: " + getResource("test.txt"));                
   }
}  

Assuming we have a text file file.txt, which has the following content −

This is TutorialsPoint!

Assuming we have another text file test.txt, which has the following content −

This is Java Tutorial

让我们编译并运行上面的程序,这将产生下面的结果 −

File1: This is TutorialsPoint!
File2: This is Java Tutorial