Read Next Byte of Data from Input Stream in Java



The method java.io.InputStream.read() is used to read the next byte of data from the input stream. This method requires no parameters and it returns the next data byte in the form of int. If the stream end is reached, it returns -1.

A program that demonstrates this is given as follows −

Example

import java.io.InputStream;
public class Demo {
   public static void main(String[] args) throws Exception {
      InputStream input = null;
      int i;
      char c;
      try {
         input = new FileInputStream("C://JavaProgram//data.txt");
         System.out.println("The characters in the file are:");
         while((i = input.read())!=-1) {
            c = (char)i;
            System.out.print(c);
         }
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

The output of the above program is as follows −

Output

The characters in the file are:
DATA
Updated on: 2019-07-30T22:30:25+05:30

404 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements