在Java中捕获标准输出的内容

Sha*_*ala 15 java stdout println

我正在调用一个在我的控制台/标准输出中打印一些字符串的函数.我需要捕获这个字符串.我不能修改正在进行打印的函数,也不能通过继承来改变运行时行为.我无法找到任何允许我这样做的预定义方法.

JVM是否存储打印内容的缓冲区?

有谁知道有助于我的Java方法?

And*_*s_D 30

您可以通过调用重定向标准输出

System.setOut(myPrintStream);
Run Code Online (Sandbox Code Playgroud)

或者 - 如果需要在运行时记录它,请将输出传递给文件:

java MyApplication > log.txt
Run Code Online (Sandbox Code Playgroud)

另一个技巧 - 如果你想重定向并且不能改变代码:实现一个快速包装器来调用你的应用程序并启动它:

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


Ing*_*ngo 5

您可以使用写入字符串缓冲区的流临时替换 System.err 或 System.out。


Kar*_*iya 5

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");

        }

    }
}
Run Code Online (Sandbox Code Playgroud)