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) All Rights Reserved.
package com.kodehelp.javaio;


 * Created by
 * Date: 4/28/11
public class InputStreamToString {

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

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