Question

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?

Était-ce utile?

La solution 2

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

Autres conseils

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

It is possible, just read from system.in and output both to system.out and a file.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top