拦截 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();
}

}

}

你可能感兴趣的:(jdk,C++,c,F#,C#)