getOutputStream() Method Example

getOutputStream() Method Example

We have seen earlier how to read and send file contents of a text file and HTML file to client. They look a little bit tedious of more code. One more style exist where all the data is converted to a binary and send to client. With the help of content type, the browser is able to convert the binary into the original file contents. With this style, any file contents like an image file, a JAR file or a HTML file etc. can be read and sent to client. It is not file download.

In the following code, a HTML file, Life.html, is read into a binary stream and sent to client (earlier also HTML file contents were sent but now completely a different style).

The new method used in the code is getResourceAsStream(String) defined in ServletContext and let us see what API says about this method.

  • InputStream getResourceAsStream(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 getOutputStream()

1st Program: HTMLFileSend.html

2nd Program: HTMLFileSend.java

getResourceAsStream(String file) method of ServletContext returns an object of InputStream. Implicitly, the InputStream object points (or refers) to the file passed as parameter.

How to use getOutputStream() method in coding?

Following statement gives.

ServletOutputStream sos = res.getOutputStream();

For all binary streams, use byte stream ServletOutputStream but not character stream PrintWriter. ServletOutputStream is more discussed in Servlet Streams to send response to Client.

res.setContentType("application/html");

Observe the MIME type as application/html. If it JAR file to read, make the MIME type as follows.

res.setContentType("application/jar");

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

There is another way of sending HTML file contents – Read HTML File Contents Example.

One thought on “getOutputStream() Method Example

  1. Surya

    sir,

    Am getting NullPointerException() eventhough i declared all correctly same as u r program.i can’t able to find my error where it is..could u please help me to sort out.
    ?

Leave a Reply

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