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

Please  SEND HTML  file.

2nd Program: RetrievingHTMLFile.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class RetrievingHTMLFile extends HttpServlet
{
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    res.setContentType("application/html"); // for JAR, it is application/jar

    ServletContext ctx = getServletContext( );
    InputStream is = ctx.getResourceAsStream("/Wishes.html" );
	  			            // place the Wishes.html file in india folder

    OutputStream os = res.getOutputStream();

    int k = 0;
    while((k = is.read()) != -1)
    {
      os.write(k);	// each byte read goes to client
    }                  //  and makes a file on the Browser
    os.flush();   
    os.close();
  }
}


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 Comment

Your email address will not be published.