Convert InputStream String Java

If you want to convert InputStream to String using java please see sample program below where we are converting InputStream to string two ways:

  • Sample java program:
package com.javahonk;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.IOUtils;

public class ConvertInputStreamString {

	public static void main(String[] args) {
		
		try {
			String stringToConvert = "Convert InputStream to String using Java";
			
			// Example 1: Using Apache Commons API
			InputStream inputStream = IOUtils.toInputStream(stringToConvert, "UTF-8");
			
			//Convert InputStream to string
			String stringVlue = IOUtils.toString(inputStream, "UTF-8");
			System.out.println("Example 1: "+stringVlue);

			//Example 2 
			InputStream stream = new ByteArrayInputStream(stringToConvert.getBytes(StandardCharsets.UTF_8));
			
			//Convert InputStream to string
			String convertedStringValue = IOUtils.toString(stream, "UTF-8");
			System.out.println("Example 2: "+convertedStringValue);				
			
		} catch (IOException e) {
			e.printStackTrace();
		}


	}

}
  • Output:

Convert InputStream String Java

For more information about InputStream in java please refer oracle documentation here

Leave a Reply

Your email address will not be published. Required fields are marked *