Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic


How To Convert InputStream To String In Java


STRING HANDLING

Here is the complete example of how to read and convert an InputStream to a String. The steps involved are:
1) I have initialized the InputStream after converting the file content to bytes using getBytes() method and then using the ByteArrayInputStreamwhich contains an internal buffer that contains bytes that may be read from the stream.
2) Read the InputStream using InputStreamReader.
3) Read InputStreamReader using BufferedReader.
4) Appended each line to a StringBuilder object which has been read byBufferedReader.
5) Finally converted the StringBuilder to String using toString() method.

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

public class Example {
   public static void main(String[] args) throws IOException {
       InputStreamReader isr = null;
       BufferedReader br = null;
       InputStream is =
            new ByteArrayInputStream("This is the content of my file".getBytes());
       StringBuilder sb = new StringBuilder();
       String content;
       try {
           isr = new InputStreamReader(is);
       br = new BufferedReader(isr);
       while ((content = br.readLine()) != null) {
        sb.append(content);
       }
    } catch (IOException ioe) {
        System.out.println("IO Exception occurred");
        ioe.printStackTrace();    
       } finally {
        isr.close();
        br.close();
          }
        String mystring = sb.toString();
    System.out.println(mystring);
   }
}
Output:

This is the content of my file

asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes
46 views



Related Hot Questions



Government Jobs Opening


...