类类getResourceAsStream()方法 (Class class getResourceAsStream() method)
getResourceAsStream() method is available in java.lang package.
getResourceAsStream()方法在java.lang包中可用。
getResourceAsStream() method is used to get the resource as a parameter and convert the resource into InputStream.
getResourceAsStream()方法用于获取资源作为参数并将资源转换为InputStream。
getResourceAsStream() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
getResourceAsStream()方法是一个非静态方法,只能通过类对象进行访问,如果尝试使用类名访问该方法,则会收到错误消息。
getResourceAsStream() method may throw an exception at the time of returning InputStream object.
返回InputStream对象时, getResourceAsStream()方法可能会引发异常。
NullPointerException: This exception may raise when the given resource_name is null.
NullPointerException :当给定的resource_name为null时,可能会引发此异常。
Syntax:
句法:
public InputStream getResourceAsStream(String resource_name);
Parameter(s):
参数:
String resource_name – represents the name of the resource.
字符串resource_name –表示资源的名称。
Return value:
返回值:
The return type of this method is InputStream, it returns the following values based on the following cases,
此方法的返回类型为InputStream ,它基于以下情况返回以下值:
It returns the InputStream, when any resource associated with the given name exists.
当存在与给定名称关联的任何资源时,它将返回InputStream 。
It returns null, when no resource associated with the given name exists.
当不存在与给定名称关联的资源时,它返回null 。
Example:
例:
// Java program to demonstrate the example
// of InputStream getResourceAsStream(String resource_name)
// method of Class
import java.io.*;
import java.util.*;
public class GetResourceAsStreamOfClass {
public static String resource(String res) {
String count = "";
try {
Class cl = Class.forName("GetResourceAsStreamOfClass");
ClassLoader loader = cl.getClassLoader();
// By using getResourceAsStream() method is to take the resource
// and convert it into InputStream
InputStream is = loader.getResourceAsStream(res);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
count = count + 1;
}
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return count;
}
public static void main(String[] args) throws Exception {
System.out.println(resource("Includehelp.doc"));
}
}
Output
输出量
Includehelp is a technical site
翻译自: https://www.includehelp.com/java/class-class-getresourceasstream-method-with-example.aspx