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

21

我正在调用一个函数,它在我的控制台/标准输出中打印一些字符串。我需要捕获这个字符串。我不能修改执行打印操作的函数,也不能通过继承改变运行时行为。我无法找到任何预定义的方法来帮助我实现。

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

有没有人知道一个能够帮助我的Java方法?


1
这似乎很不专业,尝试其他方法吧,或者换一种方式... - Tobias
可能是 https://dev59.com/jm855IYBdhLWcg3wcz_y 的重复问题。 - Kartik Domadiya
“控制台/标准输出”打印什么?请注意,使用System.setOut(myPrintStream);无法重定向System.console().writer().print()的输出。 - oliholz
3个回答

34
您可以通过调用以下方式重定向标准输出:
System.setOut(myPrintStream);

或者,如果你需要在运行时记录它,请将输出导向文件:

java MyApplication > log.txt

还有一个技巧——如果你想重定向但无法更改代码:实现一个快速包装器来调用你的应用程序并启动它:

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

5
您可以暂时将System.err或System.out替换为写入字符串缓冲区的流。

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

        }

    }
}

请查看这里:https://dev59.com/jm855IYBdhLWcg3wcz_y - Kartik Domadiya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接