标准 I/O 在 Unix 中指的是程序所使用的单一信息流。程序的所有输入都来自于标准输入、所有输出都发送到标准输出,以及所有的错误都会发送到标准错误中。这样我们可以很容易把程序串起来,一个程序的标准输出是另一个程序的标准输入,是不是很强大呀O(∩_∩)O~
1 从标准输入中读取数据
Java 的标准 I/O 模型提供了 System.in
、System.out 和 System.err。System.out 和 System.err 都已被包装成了 PrintStream 对象,但 System.in
却没有,所以我们可以直接使用 System.out 和 System.err,而在读取 System.in
之前必须先对其进行包装。
public class Echo {
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = stdin.readLine()) != null && s.length() != 0)
System.out.println(s);
// An empty line or Ctrl-Z teminates the program
}
}
注意,readLine() 会抛出 IOException。还有一点,读取 System.in
时要加入缓冲能力。
2 把 System.out 转换为 PrintWriter
public class ChangeSystemOut {
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out, true);
out.println("Hello,world");
}
}
这里使用了带两个参数的 PrintWriter 构造器。第二个参数为 true,表示开启了自动清空功能,这样才能在控制台看到实际的输出!
3 标准 I/O 的重定向
System 类提供了一些静态方法,我们可以利用这些方法对标准输入、标准输出以及错误 I/O 流进行重定向:
- setIn(InputStream)
- setOut(PrintStream)
- setErr(PrintStream)
有时候会一次性输出大量的信息,而这些输出滚动的太快以至于无法阅读时,重定向输出就很有用:
public class Redirecting {
public static void main(String[] args) throws IOException {
PrintStream console = System.out;
BufferedInputStream in = new BufferedInputStream(new FileInputStream
("D:\\temp\\1\\1.txt"));
PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream
("D:\\temp\\1\\5.txt")));
System.setIn(in);
System.setOut(out);
System.setErr(out);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = br.readLine()) != null)
System.out.println(s);
out.close();// Remember this!
System.setOut(console);
}
}
这里,我们将标准输入接入文件,然后将标准输出和标准错误重定向到另一个文件。System.out 最开始先保存在参数中,最后再恢复。这样只有中间这一段的 System.out 被做了重定向处理。
还有一点,I/O 重定向操作的是字节流,所以我们这里使用了 FileInputStream 和 FileOutputStream。