Convert inputstream to String in Java

Convert InputStream to String in Java

Converting InputStream to String in Java is a very common operation, in this post, We will cover how to Convert InputStream to String in Java using

  1. Apache Commons IOUtils
  2. Java

 

1. Apache Common

One of the clean ways to Convert InputStream to String in Java is using Apache Commons IOUtils.

public class InputStreamStringCommonIO {

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

        String sampleTestString = "Converting input stream to String using Apache Common IO";
        InputStream inputStream = new ByteArrayInputStream(sampleTestString.getBytes());

        convertUsingCopy(inputStream, StandardCharsets.UTF_8);
        convertUsingToString(inputStream, StandardCharsets.UTF_8);
    }

    public static void convertUsingCopy(final InputStream inputStream, final Charset inputEncoding) throws IOException {
        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, inputEncoding);
        System.out.println(writer.toString());
    }

    public static void convertUsingToString(final InputStream inputStream, final Charset inputEncoding) throws IOException {
        String output = IOUtils.toString(inputStream, inputEncoding);
        System.out.println(output);
    }
}

Output

Converting input stream to String using Apache Common IO

Just note that IOUtils.toString()  method does not close inputStream, you can use IOUtils.closeQuietly()  to close it.

Most of the modern project use  Apache Commons as defacto API, if you are using Apache Commons IO, this is your best option.

 

2. Java Way

If you do not have the option to use Apache Commons IO, there are multiple ways to Convert InputStream to String in Java.

    2.1 Using InputStreamReader and StringBuilder

public class ConvertByInputStreamReader {

    public static void main(String[] args) {
        String sampleTestString = "Converting input stream to String using JDK Input Stream Reader";
        InputStream inputStream = new ByteArrayInputStream(sampleTestString.getBytes());
        System.out.println(inputStream);

    }

    private static String getStringByInputStreamReader(final InputStream inputStream) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder output = new StringBuilder();

        Reader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        int character = 0;
        while ((character = streamReader.read(buffer, 0, buffer.length)) > 0) {
            output.append(buffer, 0, character);
        }
        return output.toString();
    }
}

 

    2.2 Using BufferReader and StringBuilder

public class ReadUsingBufferReader {

    public static void main(String[] args) {
        String sampleTestString = "Converting input stream to String using JDK Buffer Reader";

        InputStream inputStream = new ByteArrayInputStream(sampleTestString.getBytes());
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder outStream = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                outStream.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(outStream.toString());
    }
}

Output

Converting input stream to String using JDK Buffer Reader

 

    2.3 Using Scanner

public class ReadUsingScanner {

    public static void main(String[] args) {

        String sampleTestString = "Converting input stream to String using JDK Using Scanner";
        InputStream inputStream = new ByteArrayInputStream(sampleTestString.getBytes());

        Scanner inputScanner = new Scanner(inputStream, StandardCharsets.UTF_8.name()).useDelimiter("\A");
        String output = inputScanner.hasNext() ? inputScanner.next() : "";
        System.out.println(output);
        inputScanner.close();
    }
}

Output

Converting input stream to String using JDK Using Scanner

Google Guava provides a good alternate to Convert InputStream to String in Java.

As we saw, there are a couple of ways to convert InputStream to String in Java, it based on your preferences, personally, I prefer Apache Commons IO.

All the code of this article is available Over on Github. This is a Maven-based project.

References

  1. Apache Commons IO

Umesh

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

follow me on:

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
priya Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
priya
Guest
priya

DataInputStream consumes less amount of memory space being it is binary stream, where as BufferedReader consumes more memory space being it is character stream.