This tip will show you how to create a log file using the SaveOutput method.
===================================
import java.io.*;
class Stdout {
public static void main(String[] args) {
try {
// Start capturing characters
//into the log file.
SaveOutput.start("log.txt");
// Test it.
System.out.println(
"Here's is some stuff to stdout.");
System.err.println(
"Here's is some stuff to stderr.");
System.out.println(
"Let's throw an exception...");
new Exception().printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Stop capturing characters
//into the log file
// and restore old setup.
SaveOutput.stop();
}
}
}
class SaveOutput extends PrintStream {
static OutputStream logfile;
static PrintStream oldStdout;
static PrintStream oldStderr;
SaveOutput(PrintStream ps) {
super(ps);
}
// Starts copying stdout and
//stderr to the file f.
public static void start(
String f) throws IOException {
// Save old settings.
oldStdout = System.out;
oldStderr = System.err;
// Create/Open logfile.
logfile = new PrintStream(
new BufferedOutputStream(
new FileOutputStream(f)));
// Start redirecting the output.
System.setOut(
new SaveOutput(System.out));
System.setErr(
new SaveOutput(System.err));
}
// Restores the original settings.
public static void stop() {
System.setOut(oldStdout);
System.setErr(oldStderr);
try {
logfile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// PrintStream override.
public void write(int b) {
try {
logfile.write(b);
} catch (Exception e) {
e.printStackTrace();
setError();
}
super.write(b);
}
// PrintStream override.
public void write(
byte buf[], int off, int len) {
try {
logfile.write(buf, off, len);
} catch (Exception e) {
e.printStackTrace();
setError();
}
super.write(buf, off, len);
}
}