Java.lang.Class.getResourceAsStream() 方法
描述
java.lang.Class.getResourceAsStream() 查找具有给定名称的资源。如果未找到具有该名称的资源,则返回 InputStream 对象或 null。
声明
以下是 java.lang.Class.getResourceAsStream() 方法的声明。
public InputStream getResourceAsStream(String name)
参数
name − 这是所需资源的名称。
返回值
如果没有找到具有此名称的资源,则此方法返回 InputStream 对象或 null。
异常
NullPointerException − 如果名称为空。
示例
下面的例子展示了 java.lang.Class.getResourceAsStream() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
import java.io.*;
public class ClassDemo {
static String getResource(String rsc) {
String val = "";
try {
// input stream
InputStream i = ClassDemo.class.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

