Read Data from InputStream to a String


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 doesn't 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.


package com.javadb.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("\n"); //appende a new line
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(builder.toString());
    }
}

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: