按照标准 I/O 模型,Java 提供了 System.in,System.out 和 System.err。在整本书里,
我们已经看到了怎样用 System.out 将数据写出到标准输出,其中 System.out 已经事先
被包装成了 printStream 对象。System.err 同样也是 PrintStream,但 System.in 却
是一个没有被包装的未经加工的 InputStream。这意味尽管我们可以立即使用
System.out 和 System.err,但是在读取 System.in 之前必须对其进行包装。
通常我们会用 readLine()一次一行地读取输入,因此我们会将 System.in 包装成
BufferedReader 来使用。为此,我们必须用 InputStreamReader 把 System.in 转换成
Reader。下面这个例子将直接重复你所输入的每一行。
//: c12:Echo.java
// How to read from standard input.
// {RunByHand}
import java.io.*;
public class Echo {
public static void main(String[] args)
throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String s;
while((s = in.readLine()) != null && s.length() != 0)
System.out.println(s);
// An empty line or Ctrl-Z terminates the program
}
} ///:~
使用异常规范是因为 readLine()会抛出 IOException。注意,System.in 和大多数流
我们已经看到了怎样用 System.out 将数据写出到标准输出,其中 System.out 已经事先
被包装成了 printStream 对象。System.err 同样也是 PrintStream,但 System.in 却
是一个没有被包装的未经加工的 InputStream。这意味尽管我们可以立即使用
System.out 和 System.err,但是在读取 System.in 之前必须对其进行包装。
通常我们会用 readLine()一次一行地读取输入,因此我们会将 System.in 包装成
BufferedReader 来使用。为此,我们必须用 InputStreamReader 把 System.in 转换成
Reader。下面这个例子将直接重复你所输入的每一行。
//: c12:Echo.java
// How to read from standard input.
// {RunByHand}
import java.io.*;
public class Echo {
public static void main(String[] args)
throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String s;
while((s = in.readLine()) != null && s.length() != 0)
System.out.println(s);
// An empty line or Ctrl-Z terminates the program
}
} ///:~
使用异常规范是因为 readLine()会抛出 IOException。注意,System.in 和大多数流
一样,通常应该对它进行缓冲。