Organizational Research By

Surprising Reserch Topic

How To Convert InputStream To String In Java


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.


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) {
    } catch (IOException ioe) {
        System.out.println("IO Exception occurred");
       } finally {
        String mystring = sb.toString();

This is the content of my file

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

Related Hot Questions

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.