To do it "without modifying the existing Java code" you could write another wrapper class that reassigns System.out
appropriately and then calls the existing main class
package mypackage;
import java.io.*;
import org.apache.commons.io.output.*;
public class TeeWrapper {
public static void main(String[] args) throws Exception {
FileOutputStream logFile = new FileOutputStream("log.txt");
try {
System.setOut(new PrintStream(new TeeOutputStream(System.out, logFile)));
MyProgram.main(args);
} finally {
logFile.close();
}
}
}
(using TeeOutputStream from Apache commons-io).
You run the wrapper instead of the original class
java -classpath classfolder mypackage.TeeWrapper