|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
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! | |
Search for code examples on this site
