Capturing contents of standard output in Java

杀马特。学长 韩版系。学妹 提交于 2019-11-27 14:03:58

You could temporarily replace System.err or System.out with a stream that writes to string buffer.

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);
  }
}
Kartik Domadiya
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class RedirectIO
{

    public static void main(String[] args)
    {
        PrintStream orgStream   = null;
        PrintStream fileStream  = null;
        try
        {
            // Saving the orginal stream
            orgStream = System.out;
            fileStream = new PrintStream(new FileOutputStream("out.txt",true));
            // Redirecting console output to file
            System.setOut(fileStream);
            // Redirecting runtime exceptions to file
            System.setErr(fileStream);
            throw new Exception("Test Exception");

        }
        catch (FileNotFoundException fnfEx)
        {
            System.out.println("Error in IO Redirection");
            fnfEx.printStackTrace();
        }
        catch (Exception ex)
        {
            //Gets printed in the file
            System.out.println("Redirecting output & exceptions to file");
            ex.printStackTrace();
        }
        finally
        {
            //Restoring back to console
            System.setOut(orgStream);
            //Gets printed in the console
            System.out.println("Redirecting file output back to console");

        }

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