How to read data from InputStream to a String in Java?

Below java code shows how to read data from InputStream to a String –

/****************************************************************************************
 * Created on 09-2011Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javaio;

import java.io.*;

/**
 * Created by http://kodehelp.com
 * Date: 9/29/11
 */
public class ReadInputStreamToString {
    public static void main(String args[]){
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("/conf.ini");
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while((line = reader.readLine())!=null) {
                builder.append(line);
                builder.append("\n");
            }
            System.out.println(builder.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.