Is it possible to write a Tee in Windows batch or in Java?

情到浓时终转凉″ 提交于 2019-12-22 09:24:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!