问题
I have a Java program that I run in Windows 7 console:
java -classpath classfolder mypackage.MyProgram
This program runs for very long. Time-by-time it writes output to the console using System.out.println.
Is it possible to direct its output both to the console and into a log file in real-time without modifying the existing Java code?
If Windows 7 is unable to do that, is it possible to write a Tee utility in Java?
Is it solved in Windows 8?
回答1:
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
回答2:
The tee
command could help you but it is an Unix command. You can use this batch file as analog of tee
.
Example:
systeminfo | tee_nt.bat 1.txt
回答3:
It is possible, just read from system.in and output both to system.out and a file.
来源:https://stackoverflow.com/questions/14278504/is-it-possible-to-write-a-tee-in-windows-batch-or-in-java