Read InputStream to string via ByteArrayOutputStream and catch exception - Android java.io

Android examples for java.io:ByteArrayOutputStream

Description

Read InputStream to string via ByteArrayOutputStream and catch exception

Demo Code

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{

    public static String inStream2String(InputStream is) throws Exception {
        ByteArrayOutputStream baos = null;
        try {/*from   ww w.  j ava 2s  . co m*/
            baos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            return new String(baos.toByteArray());
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
            return null;
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }
        }

    }

}

Related Tutorials