Languages
[Edit]
EN

Java - convert PrintStream to String

6 points
Created by:
Zachariah
298

In this short article, we would like to show how to convert PrintStream to String in Java.

Quick solution:

//import java.io.ByteArrayOutputStream;
//import java.io.PrintStream;

try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
     PrintStream printStream = new PrintStream(outputStream, true, "UTF-8"))
{
     printStream.println("First message ...");
     printStream.println("Second message ...");
     printStream.println("Third message ...");

     String printText = outputStream.toString();
}

 

Practical example

To convert PrintStream to String it is necessary to use some storage to collect PrintStream output data. As that storage ByteArrayOutputStream can be used that creates an in-memory array to keep data, returning them as String on toString() method call. UTF-8 charset allows using a universal encoding that is supported by almost all operating systems and programs.

package com.examples;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;

public class Program {

    private static final String UTF8_NAME = StandardCharsets.UTF_8.name();

    public static void main(String[] args) throws IOException {

        String printText;

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             PrintStream printStream = new PrintStream(outputStream, true, UTF8_NAME))
        {
            printStream.println("First message ...");
            printStream.println("Second message ...");
            printStream.println("Third message ...");

            printText = outputStream.toString();
        }

        System.out.print(printText); // First message ...
                                     // Second message ...
                                     // Third message ...
    }
}

Example output:

First message ...
Second message ...
Third message ...

 

Alternative solutions

1. OutputStream with String constructor example

This approach converts ByteArrayOutputStream to byte array that is used to create String with constructor.

package com.example;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;

public class Program {

    private static final String UTF8_NAME = StandardCharsets.UTF_8.name();

    public static void main(String[] args) throws IOException {

        String printText;

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             PrintStream printStream = new PrintStream(outputStream, true, UTF8_NAME))
        {
            printStream.println("First message ...");
            printStream.println("Second message ...");
            printStream.println("Third message ...");

            printText = new String(outputStream.toByteArray(), UTF8_NAME);
        }

        System.out.print(printText); // First message ...
                                     // Second message ...
                                     // Third message ...
    }
}

 Example output:

First message ...
Second message ...
Third message ...

2. Custom OutputStream implementation example

This approach uses custom OutputStream implementation to convert written data to String.

package com.example;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;

public class Program {

    private static final String UTF8_NAME = StandardCharsets.UTF_8.name();

    public static void main(String[] args) throws IOException {

        String printText;

        try (OutputStream outputStream = new InMemoryOutputStream();
             PrintStream printStream = new PrintStream(outputStream, true, UTF8_NAME))
        {
            printStream.println("First message ...");
            printStream.println("Second message ...");
            printStream.println("Third message ...");

            printText = outputStream.toString();
        }

        System.out.print(printText); // First message ...
                                     // Second message ...
                                     // Third message ...
    }

    private static class InMemoryOutputStream extends OutputStream {

        private StringBuilder string = new StringBuilder();

        @Override
        public void write(int b) throws IOException {
            this.string.append((char) b );
        }

        public String toString() {
            return this.string.toString();
        }
    }
}

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join