【问题标题】:Capturing contents of standard output in Java在 Java 中捕获标准输出的内容
【发布时间】:2011-07-20 08:45:31
【问题描述】:

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

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

有人知道可以帮助我的 Java 方法吗?

【问题讨论】:

  • 这似乎很hacky,试试看。否则,另一种方法左右......
  • 什么'控制台/标准输出'打印?请注意,System.console().writer().print() 打印不会被重定向到 System.setOut(myPrintStream);

标签: java stdout println


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      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");
      
              }
      
          }
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      相关资源
      最近更新 更多