Reads string from given InputStream object - Android java.io

Android examples for java.io:InputStream

Description

Reads string from given InputStream object

Demo Code

import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main{

    /**/*from  ww  w.  j  av a  2s  .  c o  m*/
     * Reads string from given InputStream object
     *
     * @param inputStream InputStream object from which we need to read the string
     * @return The string read from the inputStream object. Null if input stream is null or read fails.
     */
    public static String readStringFromInputStream(InputStream inputStream) {

        Log.v(TAG, "readStringFromInputStream(InputStream)");

        BufferedReader bufferReader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            String line;
            bufferReader = new BufferedReader(new InputStreamReader(
                    inputStream));
            while ((line = bufferReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            Log.e(TAG, "readStringFromInputStream - Error:" + e);
        } finally {
            if (bufferReader != null) {
                try {
                    bufferReader.close();
                } catch (IOException e) {
                    Log.e(TAG, "readStringFromInputStream - Error:" + e);
                }
            }
        }
        return stringBuilder.toString();
    }

}

Related Tutorials