At times you want the output of all the System.out.println and other System.out print stuff in a log file or in a UI window somewhere. To do this, you need to wrap PrintStream, and call System.setOut and System.setErr
Example Wrapper class that provides the tee function:
private File outFile;
private PrintStream filePrint;
private boolean canLog = false;
public LogCapture(PrintStream original, String logFile) {
super(original);
outFile = new File(logFile);
try {
if (!outFile.exists())
outFile.createNewFile();
filePrint = new PrintStream(outFile);
if(outFile.canWrite())
canLog = true;
else
canLog = false;
} catch (Exception e) {
e.printStackTrace();
canLog = false;
}
}
@Override
public void write(byte buf[], int off, int len) {
try {
super.write(buf, off, len);
if (canLog)
filePrint.write(buf, off, len);
} catch (Exception e) {
}
}
@Override
public void flush() {
super.flush();
filePrint.flush();
}
}
To use:
[cc lang=”java”]
LogCapture logger = new LogCapture(System.out, logFile);
System.setOut(logger);
System.setErr(logger);