重定向输出

PrintStream 输出流:

PrintStream out = System.out;   保存输出流

System.out , System.setOut()  可以设置标准输出流.

package Example200;

import java.io.FileNotFoundException;
import java.io.PrintStream;

public class RedirectOutputStream {

    public static void main(String[] args) {
        try {
            // 保存输出流
            PrintStream out = System.out;
            PrintStream ps = new PrintStream("./log.txt");
            // 重定向输出流到文件
            System.setOut(ps);
            int age = 18;
            System.out.println("年龄变为18");
            String sex = "女";
            System.out.println("性别变为女");
            String info = "这个是" + sex + "孩子, 应该有" + age + "岁了";
            System.out.println("整合两个变量为info字符串, 结果是:" + info);
            System.out.println(out);
            System.out.println("程序运行完毕, 查看日志");
            System.setOut(out);
            System.out.println("print stream return");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
原文地址:https://www.cnblogs.com/moveofgod/p/13068749.html