|
|
|
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("
"); } } catch (IOException e) { e.printStackTrace(); } finally { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println(builder.toString()); } }
If you need any urgent assistance on Reading_A_File_Using_Inputstream_in_Java, kindly email your requirement to us at : info@javagenious.com or Contact-an-Expert. Our experts will try their best to solve your problem.
Keyword Tags: Reading_A_File_Using_Inputstream_in_Java tutorial,Reading_A_File_Using_Inputstream_in_Java in java,Concepts of Reading_A_File_Using_Inputstream_in_Java,Java,J2EE,Interview Questions,Reading_A_File_Using_Inputstream_in_Java Examples
Most programming languages compile source code directly into machine code, suitable for execution on a particular microprocessor architecture. read more
|
|
|