How to Convert an InputStream to a String in Android

In this simple android snippet code, we will going to learn how to convert an inputStream to string in android. This is a common feature that you will always encounter why working with Java and Android.

There are many different way by which this can be achieved, so we will explore some different methods we can use to achieve the same feature.

Before we start, the first thing I will do is to list the environment and tools I used in this android code snippet but feel free to use whatever environment or tools you are familiar with.

Windows 7

Android Studio

Samsung Galaxy Fame Lite

Min SDK 14

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: InputStreamToAString

Package: com.inducesmile.inputstreamtoastring

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button

Once you are done with creating your project, copy and paste the following code snippet to your project. Replace the code in your file with the following code.

Make sure you change the package name if you did not use the same package.


import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

protected void onCreate(Bundle savedInstanceState) {
String inputStreamToString = convertInputStreamToString((InputStream)inputstreamobject);

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(, menu);
return true;

public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == {
return true;
return super.onOptionsItemSelected(item);

static String convertInputStreamToString( is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A");
return s.hasNext() ? : "";

The method convertInputStreamToString takes an InputStream as parameter and it will convert the InputStream object to a String. This method uses Java Scanner API.

Another nice way to achieve this effect is to use Apache Commons IOUtils class with its copy method to copy the InputStream to a StringWriter. The code snippet below shows how it can be accomplished. Remember to import the Apache Commons to your project.

private String convertInputStreamToString( is){
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF");
String theString = writer.toString();
return theString;

Add a Comment