Sunday, 16 June 2013

Convert InputStream To String and String to InputStream in java

 package com.iandjava;  
 import java.io.BufferedReader;  
 import java.io.ByteArrayInputStream;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.InputStreamReader;  
 public class InputStreamToStringExample {  
      public static void main(final String[] args) throws IOException {  
           String content = "I and JAVA";  
           InputStream inputStream = getInputStreamFromString(content);  
           String result = getStringFromInputStream(inputStream);  
           System.out.println(result);  
      }  
      // convert String into InputStream  
      public static InputStream getInputStreamFromString(final String input) {  
           InputStream is = new ByteArrayInputStream(input.getBytes());  
           return is;  
      }  
      // convert InputStream to String  
      public static String getStringFromInputStream(final InputStream is) throws IOException {  
           BufferedReader br = null;  
           StringBuilder sb = new StringBuilder();  
           String line;  
           try {  
                br = new BufferedReader(new InputStreamReader(is));  
                while ((line = br.readLine()) != null) {  
                     sb.append(line);  
                }  
           } finally {  
                if (br != null) {  
                     br.close();  
                }  
           }  
           return sb.toString();  
      }  
 }  
profile for Ashish Aggarwal on Stack Exchange, a network of free, community-driven Q&A sites

No comments:

Post a Comment