拦截 System.out 以及 System.err

针对System.out 以及 System.err 进行拦截 比如将打印信息 输出到指定的文件:
不如 拦截 Jdk logger 的 ConsoleHandler 或者 logj4j的 ConsoleAppender 时
一下是 demo 代码:

============================================================
package com.bes.graphics;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.RandomAccessFile;

public class SystemErrInterceptor {

private SystemErrInterceptor(){
System.setErr(new SelfPrintStream());
System.setOut(new SelfPrintStream());
}

private static final SystemErrInterceptor instance = new SystemErrInterceptor();

public static final SystemErrInterceptor getInstance(){
return instance;
}


private static class SelfPrintStream extends PrintStream{

public SelfPrintStream(){
super(new SelfOutputStream());
}

@Override
public void print(boolean b) {
log(String.valueOf(b));
}

@Override
public void print(char c) {
log(String.valueOf(c));
}

@Override
public void print(char[] s) {
log(new String(s));
}

@Override
public void print(double d) {
log(String.valueOf(d));
}

@Override
public void print(float f) {
log(String.valueOf(f));
}

@Override
public void print(int i) {
log(String.valueOf(i));
}

@Override
public void print(long l) {
log(String.valueOf(l));
}

@Override
public void print(Object obj) {
log(String.valueOf(obj));
}

@Override
public void print(String s) {
log(s);
}

@Override
public void println() {
log("\n");
}

@Override
public void println(boolean x) {
log(x + "\n");
}

@Override
public void println(char x) {
log(x + "\n");
}

@Override
public void println(char[] x) {
log(new String(x) + "\n");
}

@Override
public void println(double x) {
log(x + "\n");
}

@Override
public void println(float x) {
log(x + "\n");
}

@Override
public void println(int x) {
log(x + "\n");
}

@Override
public void println(long x) {
log(x + "\n");
}

@Override
public void println(Object x) {
log(x + "\n");
}

@Override
public void println(String x) {
log(x + "\n");
}



}


private static class SelfOutputStream extends ByteArrayOutputStream{

@Override
public synchronized void write(byte[] b, int off, int len) {
log(String.valueOf(b));
}

@Override
public synchronized void write(int b) {
log(String.valueOf(b));
}

@Override
public void write(byte[] b) throws IOException {
log(String.valueOf(b));
}

}


/**
* @param obj
*/
private static void log(Object obj){
try{
File f = new File("c:/a.log");
if(!f.exists()){
f.createNewFile();
}
RandomAccessFile raf = new RandomAccessFile(f, "rw");
raf.seek(raf.length());
String msg = obj + "\r\n";
raf.write(msg.getBytes("utf-8"));
}catch(Exception ex){
ex.printStackTrace();
}

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值