In this section we will discuss about the InputStream in Java.
In this section we will discuss about the InputStream in Java.In this section we will discuss about the InputStream in Java.
An abstract class InputStream is a base class of all the byte stream classes which acts as an input stream of bytes. This class is provided in the java.io package. There are various of subclasses which extends InputStream class. Commonly used classes are as follows :
Constructor of this class is as follows :
InputStream()
Commonly used Methods of InputStream class are as follows :
Example :
An example is being given here which demonstrates how to read data input stream using the InputStream. To read the input stream we must have a source from where the stream can be read by the InputStream so I have created a text file and write some texts into them. In the example I have created a reference of InputStream and used the FileInputStream to read the data input stream as byte. Then after reading the data from the text file displayed it on the console.
Source Code
/*This example demonstrates that how to read the data input stream*/ import java.io.InputStream; import java.io.FileInputStream; import java.io.IOException; public class InputStreamExample { public static void main(String args[]) { InputStream is = null; try { is = new FileInputStream("read.txt"); int c; System.out.println(); System.out.println("reading text....."); while((c = is.read() ) != -1) { System.out.println((char) c); } System.out.println(); } catch(IOException ioe) { System.out.println(ioe); } finally { if(is != null) { try { is.close(); } catch(Exception e) { System.out.print(e); } } }// end finally }// end main }// end class
Output :
To execute the above example you would be required to compile it first and then execute. An image given below demonstrates you that how to compile and execute the above example and the output of the above example after successfully execution.
You can download the source code from the link given below. The downloaded file will contained the two files one for the source code and the other is the text file from which input stream is read.
Ads