Sunday, June 10, 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 String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
   
Reader reader = null;
    reader
= new InputStreamReader(stream, "UTF-8");        
   
char[] buffer = new char[len];
    reader
.read(buffer);
   
return new String(buffer);
}


No comments:

Post a Comment