Java中的类 getResourceAsStream() 方法和示例
Java.lang.Class类的getResourceAsStream()方法用于获取该类指定资源的资源。该方法以 InputStream 对象的形式返回该类的指定资源。
句法:
public InputStream getResourceAsStream(String resourceName)
参数:此方法接受参数resourceName ,即要获取的资源。
返回值:该方法以InputStream对象的形式返回该类的指定资源。
异常此方法抛出:
- 如果名称为空,则出现NullPointerException
下面的程序演示了 getResourceAsStream() 方法。
示例 1:
// Java program to demonstrate
// getResourceAsStream() method
import java.util.*;
public class Test {
public Object obj;
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Test");
System.out.println("Class represented by myClass: "
+ myClass.toString());
String resourceName = "obj";
// Get the resource of myClass
// using getResourceAsStream() method
System.out.println(
resourceName + " resource of myClass: "
+ myClass.getResourceAsStream(resourceName));
}
}
输出:
Class represented by myClass: class Test
obj resource of myClass: null
示例 2:
// Java program to demonstrate
// getResourceAsStream() method
import java.util.*;
class Main {
private Object obj;
public static void main(String[] args)
throws ClassNotFoundException, NoSuchFieldException
{
// returns the Class object for this class
Class myClass = Class.forName("Main");
System.out.println("Class represented by myClass: "
+ myClass.toString());
String resourceName = "obj";
try {
// Get the resource of myClass
// using getResourceAsStream() method
System.out.println(
resourceName + " resource of myClass: "
+ myClass.getResourceAsStream(resourceName));
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Class represented by myClass: class Main
obj resource of myClass: null
参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getResourceAsStream-java.lang.String-