Java

How to Convert InputStream to String

admin  

[tweet-dzone]Sometimes I feel there are too many classes in java to work with streams and files. InputStream is the base class of all the classes in Java IO API. The input stream class is intended to be used to read the data from different sources in chunks. This is useful for large streams that don't fit in memory.

Lots of libraries returns objects of type InputStream and sometimes you know the stream small and you just need the data as a simple String. Here is the snippet written as a static method to transfer the data from a InputStream to a String.

The method reads the InputStream line by line (using BufferedReader.readLine()) until the null line is encountered. It appends each line to a StringBuilder object for optimal performance and returns it as a String:

/**
     * method to convert an InputStream to a string using the BufferedReader.readLine() method
     * this methods reads the InputStream line by line until the null line is encountered
     * it appends each line to a StringBuilder object for optimal performance 
     * @param is
     * @return
     * @throws IOException
     */
    public static String convertInputStreamToString(InputStream inputStream) throws IOException 
    {
        if (inputStream != null) 
        {
            StringBuilder stringBuilder = new StringBuilder();
            String line;

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                while ((line = reader.readLine()) != null) 
                {
                    stringBuilder.append(line).append("\n");
                }
            }
            finally 
            {
                inputStream.close();
            }

            return stringBuilder.toString();
        }
        else
        {        
            return null;
        }
    }	
    Java