Java标准输入/输出/错误流

只要使用OutputStream对象就可使用System.outSystem.err对象引用。只要可以使用InputStream对象就可以使用System.in对象。

System类提供了三个静态设置器方法setOut()setIn()stdErr(),以用自己的设备替换这三个标准设备。

要将所有标准输出重定向到一个文件,需要通过传递一个代表文件的PrintStream对象来调用setOut()方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.File;
 
public class Main {
  public static void main(String[] args) throws Exception {
    File outFile = new File("stdout.txt");
    PrintStream ps = new PrintStream(new FileOutputStream(outFile));
 
    System.out.println(outFile.getAbsolutePath());
 
    System.setOut(ps);
 
    System.out.println("Hello world!");
    System.out.println("Java I/O  is cool!");
  }
}

上面的代码生成以下结果。

1
F:websitesxtworkspstdout.txt
 
原文地址:https://www.cnblogs.com/hane/p/7305650.html