How To Convert InputStream to String in Java

Below Java code show how to read the file in InputStream and convert the inputStream to String. In this example the file used (“TEST.txt”) is kept in the root directory of your project.


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

import java.io.*;

/**
 * Created by https://kodehelp.com
 * Date: 4/28/11
 */
public class InputStreamToString {

    public static void main(String[] args) throws Exception{
        InputStream is = new FileInputStream("/demo.java");
        StringBuffer buffer = new StringBuffer();
        byte[] b = new byte[1024];
        int n;
         while ((n = is.read(b)) != -1) {
            buffer.append(new String(b, 0, n));
         }
        String str = buffer.toString();
        System.out.println(str);
    }
}

Output of this example of content of file printed as string on console.