Home » Java programming language

Java ClassLoader getSystemResourceAsStream() method with example

ClassLoader Class getSystemResourceAsStream() method: Here, we are going to learn about the getSystemResourceAsStream() method of ClassLoader Class with its syntax and example.
Submitted by Preeti Jain, on November 28, 2019

ClassLoader Class getSystemResourceAsStream() method

  • getSystemResourceAsStream() method is available in java.lang package.
  • getSystemResourceAsStream() method is used to get the resource as a parameter and convert the resource into InputStream or in other words we can say this method is used to represent InputStream for scanning the given resource.
  • getSystemResourceAsStream() method is a static method, it is accessible with the class name and if we try to access the method with the class object then we will not get any error.
  • getSystemResourceAsStream() method does not throw an exception at the time of conversion from resource to InputStream object.

Syntax:

    public static InputStream getResourceAsStream(String resource_name);

Parameter(s):

  • String resource_name – represents the name of the resource.

Return value:

The return type of this method is InputStream, it returns the following values based on the given cases,

  • It returns the InputStream when any system resource associated with the given name exists.
  • It returns null, when no system resource associated with the given name exists.

Example:

// Java program to demonstrate the example 
// of InputStream getSystemResourceAsStream(String resource_name) 
// method of  ClassLoader 

import java.io.*;

public class GetSystemResourceAsStreamOfClassLoader {
    static String resource(String res) {
        String count = "";
        try {
            Class cl = Class.forName("GetSystemResourceAsStreamOfClassLoader");
            ClassLoader loader = cl.getClassLoader();

            // By using getSystemResourceAsStream() method is to take the 
            //resource and convert it into InputStream
            InputStream is = loader.getSystemResourceAsStream(res);
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            String line;
            while ((line = br.readLine()) != null) {
                count = count + line;
            }
            is.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(resource("getProperties().doc"));
    }
}

Output

File Writing Done!!


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.