Java: PrintStream to String?

前端 未结 6 973
半阙折子戏
半阙折子戏 2021-01-30 15:10

I have a function that takes an object of a certain type, and a PrintStream to which to print, and outputs a representation of that object. How can I capture this f

6条回答
  •  野性不改
    2021-01-30 15:50

    You can construct a PrintStream with a ByteArrayOutputStream passed into the constructor which you can later use to grab the text written to the PrintStream.

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(os);
    ...
    String output = os.toString("UTF8");
    

提交回复
热议问题