ServletContext getResourceAsStream()

ServletContext getResourceAsStream()

Using the method getResourceAsStream(), a Servlet can use any file on the system (or Web application in WEB-INF folder) and load it. To load, the Sevlet container does not need a traditional class loader. This method returns an object of InputStream that refers the file passed as parameter. The InputStream (a byte stream) object can be used to read the file. Better suitable to read and send to client like image files, HTML files etc. where lot of image and word processing is done.

ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream(“/filename”);

The method returns null if no file is found. The file name should be preceded by a forward slash ("/") which indicates the file is available in a folder relative to the current context root directory.

What Servlet API says about this method:

  • java.io.InputStream getResourceAsStream(java.lang.String path) : Returns the resource located at the named path as an InputStream object. The data in the InputStream can be of any type or length. This method returns null if no resource exists at the specified path.
Example on ServletContext getResourceAsStream()

To send file contents to client. The file can be of any format and best suitable for images, HTML, JAR etc. where lot of formatting exists. When we execute this program, it asks on which directory to save the file on the client system. When the directory is given, it is saved in that directory.

1st Program: RetrievingHTMLFile.html

2nd Program: RetrievingHTMLFile.java


ServletContext getResourceAsStream()
Output screen on ServletContext getResourceAsStream()

The same Wishes.html file contents are sent to client earlier to client in a different way but laborious.

Note: PrintWriter should be not used when OutputStream is used. Only one stream can be used.

Note: There is exactly a similar method available – java.lang.Class.getResourceAsStream(). This is very different in that this method requires a class loader to load the class.

Leave a Reply

Your email address will not be published. Required fields are marked *