2011-03-22 87 views
11

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

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

有谁知道一种Java方法可以帮助我吗?

+1

这似乎很hacky,试一下。否则,另一种方法或左右... – Tobias 2011-03-22 10:12:17

+0

可能重复http://stackoverflow.com/questions/4334808/how-could-i-read-java-console-output-into-a-string-buffer – 2011-03-22 10:25:28

+0

什么'控制台/标准输出“打印?注意'System.console().writer().print()'打印不会被重定向到'System.setOut(myPrintStream);' – oliholz 2011-03-22 11:08:36

回答

2

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

28

你可以通过调用

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

     } 

    } 
} 
+0

check [here](http://stackoverflow.com/questions/4334808/如何-可能,我读的Java控制台输出 - 到 - 一个字符串缓冲区) – 2011-03-22 10:21:20

相关问题