ClassLoader.getSystemResourceAsStream() 方法

描述

java.lang.ClassLoader.getSystemResourceAsStream() 方法打开读取,从用于加载类的搜索路径中指定名称的资源。


声明

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

public static InputStream getSystemResourceAsStream(String name)

参数

name − 这是资源名称。


返回值

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


异常

NA


示例

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

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.getSystemResourceAsStream(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