Read keyboard input with BufferedInputStream in Java

Description

The following code shows how to read keyboard input with BufferedInputStream.

Example


/*w  w  w  .  ja v  a 2s.  c  o m*/
import java.io.BufferedInputStream;
import java.io.IOException;

public class Main {
  public static String readLine() {
    StringBuffer response = new StringBuffer();
    try {
      BufferedInputStream buff = new BufferedInputStream(System.in);
      int in = 0;
      char inChar;
      do {
        in = buff.read();
        inChar = (char) in;
        if ((in != -1) & (in != '\n') & (in != '\r')) {
          response.append(inChar);
        }
      } while ((in != -1) & (inChar != '\n') & (in != '\r'));
      buff.close();
      return response.toString();
    } catch (IOException e) {
      System.out.println("Exception: " + e.getMessage());
      return null;
    }
  }

  public static void main(String[] arguments) {
    System.out.print("\nWhat is your name? ");
    String input = readLine();
    System.out.println("\nHello, " + input);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip