Convert InputStream to String in Java - Java @ Desk

Friday, March 21, 2014

Convert InputStream to String in Java

Convert InputStream to String in Java

In java, when we perform file operations like reading from a file using java.io.InputStream & java.io.FileInputStream, we pass a file object and the java.io.InputStream object gives us the input stream.

What if we want to convert this input stream and display to content on a web page or store it in a string for further utilization.

Here is a simple example to convert input stream to String

Input String - Degree education on ine, Buy Domain Name, Car Insurance, Online Accounting Degree

package com.file;

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

public class InputStreamToString {
 public static void main(String[] args) throws IOException {
  
  String originalString = "Student Loan Consolidation Calculator, Car Insurance, " +
    "Home improvement loan rates";
  
  InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
  
  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
  String outputString = "";
  StringBuffer stringBuffer = new StringBuffer();
  
  while ((outputString = bufferedReader.readLine()) != null) {
   stringBuffer.append(outputString);
  }
  
  System.out.println(stringBuffer.toString());
 }
}






No comments:

Post a Comment