Redirect stdout to a string in Java

前端 未结 1 1280
生来不讨喜
生来不讨喜 2020-12-13 02:24

I know how to redirect the stdout to a file, but I have no idea on how to redirect it to a string.

相关标签:
1条回答
  • 2020-12-13 03:00

    Yes - you can use a ByteArrayOutputStream:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    System.setOut(new PrintStream(baos));
    

    Then you can get the string with baos.toString().

    To specify encoding (and not rely on the one defined by the platform), use the PrintStream(stream, autoFlush, encoding) constructor, and baos.toString(encoding)

    If you want to revert back to the original stream, use:

    System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
    
    0 讨论(0)
提交回复
热议问题