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.

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.

Search for more Java info on this site here:
Custom Search

Please type any questions here.