Way2Java

Keyboard Input DataInputStream

In keyboard reading, three programs are given using DataInputStream, BufferedReader and Scanner. Of all, using java.util.Scanner is the easier and includes many methods to check the input data is valid to read.

Example on Keyboard Input DataInputStream

Following program uses readLine() method of DataInputStream to read data from the keyboard.

import java.io.*;
public class KeyboardReading1
{
  public static void main(String args[]) throws IOException
  {
    DataInputStream dis = new DataInputStream(System.in);
    System.out.println("Enter your name: ");
    String str1 = dis.readLine();
    System.out.println("I know your name is " + str1);

    System.out.println("Enter a whole number: ");
    String str2 = dis.readLine();
    int x = Integer.parseInt(str2);

    System.out.println("Enter a double value: ");
    String str3 = dis.readLine();
    double y = Double.parseDouble(str3);

    if(x > y)
      System.out.println("First number " +x + " is greater than second number " + y);
    else
      System.out.println("First number " +x + " is less than second number " + y);

    dis.close();
  }
}


Output screenshot on Keyboard Input DataInputStream

The readLine() method of DataInputStream reads a line at a time and returns as a string, irrespective of what the line contains. Depending on the input value, the string is to be parsed into an int or double etc. This is extra work in the keyboard reading when compared to C/C++. In C/C++, parsing is done implicitly by %d and %f etc.

Note: This program compilation raises deprecation warning (observe the screen shot) as readLine() method of DataInputStream is deprecated, but the program works.

What is "System.in"?

" in" is an object of " InputStream" class defined in System class (like "out" is an object of PrintStream class defined in System class). It is declared as static and final object. The in object is connected implicitly to the " standard input stream" of the underlying OS.

DataInputStream dis = new DataInputStream(System.in);

System.in is a byte stream which is automatically connected to the keyboard reading mechanism of operating system. It is a low-level byte stream. The low-level byte stream is passed to high-level byte stream DataInputStream following the rules of chaining. It is chained to DataInputStream to facilitate the reading of user input with it 's readLine() method.

Like System.in is connected to the keyboard mechanism of OS, the System.out is connected to the standard output mechanism of OS.