Java: PrintStream to String?

前端 未结 6 912
半阙折子戏
半阙折子戏 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 16:03

    A unification of previous answers, this answer works with Java 1.7 and after. Also, I added code to close the Streams.

    final Charset charset = StandardCharsets.UTF_8;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos, true, charset.name());
    yourFunction(object, ps);
    String content = new String(baos.toByteArray(), charset);
    ps.close();
    baos.close();
    

提交回复
热议问题