Java: PrintStream to String?

前端 未结 6 919
半阙折子戏
半阙折子戏 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:12

    Use a ByteArrayOutputStream as a buffer:

    import java.io.ByteArrayOutputStream;
    import java.io.PrintStream;
    import java.nio.charset.StandardCharsets;
    
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final String utf8 = StandardCharsets.UTF_8.name();
        try (PrintStream ps = new PrintStream(baos, true, utf8)) {
            yourFunction(object, ps);
        }
        String data = baos.toString(utf8);
    

提交回复
热议问题