Search This Blog

Sunday, 10 June 2012

converting InputStream to string

We are very much aware about InputStream. InputStream is to  read to content from file or URL. If we handle file then we used FileInputStream and while reading from a URL, we used InputStream.


InputStream is a readable source of bytes. Once you get an InputStream it's common to decode or convert it into a target data type. For example, if you were downloading image data, you might decode and display it directly Read this post to know how to convert input stream to bitmap See How to convert InputStream to bitmap. But if we want to convert InputStream to string then we need to read it line by line like given code


// Reads an InputStream and converts it to a String.
  public static String convertStreamToString(InputStream is) throws Exception {
 BufferedReader reader = new BufferedReader(new InputStreamReader(is));
 StringBuilder sb = new StringBuilder();
 String line = null;
 while ((line = reader.readLine()) != null) {
     sb.append(line);
  }
       is.close();
 return sb.toString();
 }


No comments:

Post a Comment

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code