Servlet – Input Stream Class
Last Updated :
30 Jun, 2022
ServletInputStream class is a component of Java package javax.servlet, It is an abstract class that provides an input stream for reading binary data from a client request, including an efficient readLine method for reading data one line at a time.
Syntax:
public abstract class ServletInputStream extends InputStream
Constructor
ServletInputStream() : Since ServletInputStream is an abstract class therefore it cannot be initialized.
Note : ServletRequest.getInputStream() method is used to get the reference of ServletInputStream.
Methods
ServletInputStream contains only one concrete method named as readLine.
readLine(byte [ ] b, int offset, int len):
- It is a part of ServletInputStream class.
- It is used to read the input stream.
- It will return a number of bytes read or -1.
- It might throw IOException if an input or output exception occurs.
Method Signature:
public int readLine(byte[] b, int offset,int len) throws IOException.
Method Parameters: readLine() method has three parameters which are byte, int, and int type.
Method Return Type: readLine() method has an int return type and will return a number of bytes read or -1 if the end of the stream is reached.
Abstract Methods of ServletInputStream
S.No.
|
Method
|
Description
|
Return Type
|
1. |
isFinished() |
isFinished() method will return true if all the data from the stream has been read otherwise it will return false. |
abstract boolean |
2. |
isReady() |
isReady() method will return true if the data from the stream can be read without blocking otherwise it will return false. |
abstract boolean |
3. |
setReadListener(ReadListener readListener) |
setReadListener method is used to instruct the ServletInputStream
to invoke the provided ReadListener when it is possible to read.
|
abstract void |
Interfaces Implemented by ServletInputStream
- java.io.Closeable .
- java.lang.AutoCloseable .
Java Program to Create a Servlet and to Check if Data of the Stream can be Read:
Java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GeeksForGeeks extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
try {
ServletInputStream servletInputStream
= request.getInpuStream();
System.out.println(
"Data of stream can be read : "
+ servletInputStream.isReady());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
{
doGet();
}
}
|
Output:
true
Note: The above code will not run on online IDE since this is server-side code.
Share your thoughts in the comments
Please Login to comment...