今天在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输出。