重定向输出流实现程序日志

来源:互联网 发布:js页面初始化方法 编辑:程序博客网 时间:2024/05/18 06:19
package 基本语法;

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=19;
System.out.println("年龄变量定义成功,初始值为19");
String sex="女";
System.out.println("性别变量定义成功,初始值为女");
String info="这是个"+sex+"孩子,应该有"+age+"岁了.";
System.out.println("整合两个变量为info字符串变量,其结果是:"+info);
System.setOut(out);//恢复原有的输出流
System.out.println("程序运行完毕,请检查日志文件。");
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
}

关键技术:setOut()方法

用于重新分配System类的标准输出流。

setErr()方法

用于重新分配System类的标准错误输出流。

setIn()方法

用于重新设置System类的in成员变量,及标准输入流。

0 0
原创粉丝点击