Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Java捕获标准输出的内容_Java_Stdout_Println - Fatal编程技术网

用Java捕获标准输出的内容

用Java捕获标准输出的内容,java,stdout,println,Java,Stdout,Println,我调用的函数正在控制台/标准输出中打印一些字符串。我需要捕捉这个字符串。我不能修改正在进行打印的函数,也不能通过继承更改运行时行为。我找不到任何预定义的方法来允许我这样做 JVM是否存储打印内容的缓冲区 有谁知道一个Java方法可以帮助我吗?您可以通过调用 System.setOut(myPrintStream); 或者-如果需要在运行时对其进行日志记录,请将输出通过管道传输到文件: java MyApplication > log.txt 另一个技巧-如果您想重定向并且无法更改代码

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

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


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

您可以通过调用

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

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

这似乎很有问题,请尝试其他方法,或者其他方法……可能与“控制台/标准输出”打印重复?请注意,
System.console().writer().print()
打印将不会使用
System.setOut(myPrintStream)重定向检查
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");

        }

    }
}