java重定向标准IO2007-05-29 yycnet.yeah.net yyc译Java 1.1在System类中添加了特殊的方法,允许我们重新定向标准输入、输出以及错误IO流。此时要用到下述简单的静态方法调用:
setIn(InputStream)
setOut(PrintStream)
setErr(PrintStream)
如果突然要在屏幕上生成大量输出,而且滚动的速度快于人们的阅读速度,输出的重定向就显得特别有用。在一个命令行程序中,如果想重复测试一个特定的用户输入序列,输入的重定向也显得特别有价值。下面这个简单的例子展示了这些方法的使用:
//: Redirecting.java// Demonstrates the use of redirection for // standard IO in Java 1.1import java.io.*;class Redirecting {public static void main(String[] args) {try {BufferedInputStream in = new BufferedInputStream(new FileInputStream("Redirecting.java"));// Produces deprecation message:PrintStream out =new PrintStream(new BufferedOutputStream(new FileOutputStream("test.out")));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!} catch(IOException e) {e.printStackTrace();}}} ///:~
这个程序的作用是将标准输入同一个文件连接起来,并将标准输出和错误重定向至另一个文件。
这是不可避免会遇到“反对”消息的另一个例子。用-deprecation标志编译时得到的消息如下:
Note:The constructor java.io.PrintStream(java.io.OutputStream) has been deprecated.
注意:不推荐使用构建器java.io.PrintStream(java.io.OutputStream)。
然而,无论System.setOut()还是System.setErr()都要求用一个PrintStream作为参数使用,所以必须调用PrintStream构建器。所以大家可能会觉得奇怪,既然Java 1.1通过反对构建器而反对了整个PrintStream,为什么库的设计人员在添加这个反对的同时,依然为System添加了新方法,且指明要求用PrintStream,而不是用PrintWriter呢?毕竟,后者是一个崭新和首选的替换措施呀?这真令人费解。