Wednesday, June 13, 2012

How to convert InputStream to String in Java?

/**
 *
 */
package convert.stream.to.string;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author abdul
 *
 */
public class StreamToString {

    /**
     * @param args
     */
    public static void main(String[] args) {
        StreamToString streamToString = new StreamToString();
     
        //intilize an InputStream
        InputStream is = new ByteArrayInputStream("file content:\nData1\nData2".getBytes());
     
        /*
         * Call the method to convert the stream to string
         */
        System.out.println(streamToString.convertStreamToString(is));
    }

    private String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}



Output:
file content:
Data1
Data2



No comments:

Post a Comment

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...