Java Program to read the next byte of data from the input stream

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 28-Feb-2019 11:45:15
Advertisements