在文件中写入System.out.println的内容

今天在coding过程中遇到了这么一件事,在J2SE程序中引入的另一个jar包的日志用的既不是log4j,也不是slf4j,而是奇怪的System.out.println。可是我想把他打印出来的信息记录到我的log文件里面,怎么办呢?于是查看API发现,System这个类可以自己指定out输出流,于是乎,下面的代码就出现了。

PrintStream p = new PrintStream(new BufferedOutputStream(new FileOutputStream("D:\\log.txt")));
System.setOut(p);
System.out.println("here we r");
p.close();

似乎可以用。

再来优化一下:

public class Test implements Runnable{
	
	public void run(){
		int i=0;
		while(true){
			System.out.println(i++);
			try {
				Thread.sleep(1000L);
			} catch (InterruptedException e) {
				
			}
		}
	}
	
	public static void main(String[] ag) throws Exception {
		PrintStream p = new PrintStream(new BufferedOutputStream(new FileOutputStream("D:\\log.txt")));
		System.setOut(p);
		new Thread(new Test()).start();//another thread test, instead of the other jar service
		try{
			while(true){
				System.out.flush();
				try {
					Thread.sleep(5000L);
				} catch (InterruptedException e) {
				
				}
			}
		}catch(Exception e){
			
		}finally{
			p.close();
		}
	}
}

 这样,每5秒钟,会将输出流中的数据保存到文件一次,不管是当前线程的out输出,还是其他线程的out输出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值