This code example shows how to read data from an InputStream object and ultimately store it in a String object.To read data from our file we use the method getResourceAsStream() which we get from our class object.The class object is retrieved by calling getClass() on our Main class.The method getResourceAsStream() enables us to read a file located within the same jar-file as the actual program, in case it is packaged as such.
It can also be used to read from the root directory of the application as done in the example by adding a slash before the filename.

Finally we use a BufferedReader to read from the stream line by line in a loop and append each line read to a StringBuilder object.
Since the method readLine() of the BufferedReader doesnt include the line breaks in the file we append a line break after appending the actual line data.

Finally the contents of the StringBuilder is printed out by converting the StringBuilder to a String using its toString() method.

Code Examples:Read Data from InputStream to a String

package com.javagenious.examples;

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

public class Main {

    public static void main(String[] args) {
        Main m = new Main();

        InputStream inStream = m.getClass().getResourceAsStream("/myTextFile.txt");

        BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
        StringBuilder builder = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(" "); //appende a new line
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(builder.toString());
    }
}




Sandeep Joshi
Mathematics, Technology and Programming are my passion. I am a part of Java Ecosystem and through this blog, I contribute to it. I am here to blog about my interests, views and experiences.
I am on Google+ and Facebook.
I feel proud to be listed as a "National Memory Record Holder" in the Limca Book of Records, 2009 and have attempted for an International Memory record in the Guiness Book of Records. I can remember the value of PI upto 10,000 digits after the decimal (3.1415.....). You can contact me on javagenious.com(At)gmal.com ; I would like to hear from you :)