Pages

Streams programmes

// This program is used to read a string
import java.io.*;
class Reading
{
  public static void main(String args[])
  {
   /* pass address of keyboard to the constructor of DataInputStream class as an object of InputStream class.In the System class, “in” is a static reference of InputStream class that contains the address of console */
    DataInputStream dis = new DataInputStream(System.in);
    System.out.println(“Enter Your Name “);
    String s = dis.readLine(); // readLine() returns input as a String
    System.out.println(“Welcome  “ + s);
  }// end of main
}// end of class

->But, it is noted that the readLine() method in the above program is defined to throw Exception,so it should be defined in try-catch block. But, when we use try-catch block, the compiler will display a message that we are using a deprecated method.So, it will be better using readLine() method in java.io.BufferedReader class.
NOTE: The constructor of BufferedReader class does not accept object of InputStream class.Instead, it accepts the object of InputStreamReader class. The constructor of the InputStreamReader class is defined to accept the object of InputStream class.
->The following program demonstrates the use of readLine() method of BufferedReader class.
/* Program to accept input from keyboard through readline() of BufferedReader. */
import java.io.*;
class ReadInput
{
  public static void main(String args[]) throws Exception
 {
   InputStreamReader isr = new InputStreamReader(System.in);
   BufferedReader br = new BufferedReader(isr);
   System.out.println(“Enter some text “);
  String msg = br.readLine();
  System.out.println(“The entered text is “ + msg);
 }
}
Eg : 2)
/* Program to accept two values from keyboard and display their sum */
import java.io.*;
class InputNumber
{
  public static void main(String args[]) throws Exception
 {
   InputStreamReader isr = new InputStreamReader(System.in);
   BufferedReader br = new BufferedReader(isr);
   System.out.println(“Enter First Number  “);
   int a = Integer.parseInt(br.readLine());
   System.out.println(“Enter Second Number  “);
   int b = Integer.parseInt(br.readLine());
   int c = a + b;
   System.out.println(“Sum is “ + c);
 }
}