Java: PrintStream to String?

前端 未结 6 907
半阙折子戏
半阙折子戏 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");
    
    0 讨论(0)
  • 2021-01-30 15:51

    Define and initialize a Scanner variable named inSS that creates an input string stream using the String variable myStrLine.

    Ans: Scanner inSS = new Scanner(myStrLine);

    0 讨论(0)
  • 2021-01-30 15:58

    Why don't you use a StringWriter with a PrintWriter?

    StringWriter writer = new StringWriter();
    PrintWriter out = new PrintWriter(writer);
    out.println("Hello World!");
    String output = writer.toString();
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2021-01-30 16:11

    Maybe this question might help you: Get an OutputStream into a String

    Subclass OutputStream and wrap it in PrintStream

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题