标准 I/O 重定向

Java 的 System 类提供一些简单的静态方法调用,允许我们对标准输入、输出和错误 I/O
流进行重定向:


setIn(InputStream)
setOut(PrintStream)
setErr(PrintStream)


如果我们突然开始在显示器上创建大量输出,而这些输出滚动的如此之快以至于无法阅读
时,重定向输出就显得极为有用4。对于“我们想重复测试特定用户的输入序列”的命令行程
序来说,重定向输入就很有价值。下例简单演示了这些方法的使用:


//: c12:Redirecting.java
// Demonstrates standard I/O redirection.
// {Clean: test.out}
import java.io.*;


public class Redirecting {

    // Throw exceptions to console:

 public static void main(String[] args)
  throws IOException {
    PrintStream console = System.out;
        BufferedInputStream in = new BufferedInputStream(
      new FileInputStream("Redirecting.java"));
    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!
    System.setOut(console);
    } 
} ///:~


这个程序将标准输入附加在文件上,并将标准输出和标准错误重定向到另一个文件。


I/O 重定向操纵的是字节流,而不是字符流,因此我们使用的是 InputStream
OutputStream 而不是 Reader 和 Writer。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值