Reading data from standard input

Source: Internet
Author: User
Tags readline

Based on the concept of "standard input", "standard output", and "standard error Output" pioneered by UNIX, Java provides the corresponding system.in,system.out and System.err. Through this whole book, everyone will touch on how to use System.out for standard output, it has been encapsulated into a PrintStream object. System.err is also a printstream, but System.in is an original inputstream, without any encapsulation processing. This means that although you can use System.out and system.err directly, you must encapsulate the system.in in advance, otherwise you cannot read data from it.
Typically, we want to use ReadLine () to read one row of input information at a time, so we need to encapsulate system.in into a datainputstream. This is the "old" approach taken by Java 1.0 for row input. Later in this chapter, you will also see the solution for Java 1.1. Here's a simple example of how to respond to each line of text we type:

: Echo.java
//How to read from standard input
import java.io.*;

public class Echo {public
  static void Main (string[] args) {
    DataInputStream in =
      new DataInputStream (
        NE W Bufferedinputstream (system.in));
    String s;
    try {while
      (s = in.readline ()). Length ()!= 0)
        System.out.println (s);
      An empty line terminates of the program
    } catch (IOException e) {
      e.printstacktrace ();}}}
/// :~

The reason to use a try block is because ReadLine () may "throw" a ioexception. Note that, like most other streams, system.in should also be buffered.
It is a bit inconvenient to encapsulate system.in into a datainputstream in every program. But with this design, you get the most flexibility.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.