Capturing contents of standard output in Java

前端 未结 3 1939
情话喂你
情话喂你 2020-12-01 11:07

I am invoking a function that is printing some string in my console/standard output. I need to capture this string. I cannot modify the function that is doing the printing,

3条回答
  •  一生所求
    2020-12-01 11:49

    You can redirect the standard output by calling

    System.setOut(myPrintStream);
    

    Or - if you need to log it at runtime, pipe the output to a file:

    java MyApplication > log.txt
    

    Another trick - if you want to redirect and can't change the code: Implement a quick wrapper that calls your application and start that one:

    public class RedirectingStarter {
      public static void main(String[] args) {
        System.setOut(new PrintStream(new File("log.txt")));
        com.example.MyApplication.main(args);
      }
    }
    

提交回复
热议问题