Convert String to Stream to String

Convert String to Stream to String

In java programming language, String is most widely used class. In certain situations we need to convert String to stream and vice versa. One such scenario is while reading data from a file, we have to convert stream to String. In this blog, we will see how to convert String to Stream and vise versa.You can learn more about String and other classes related with String like StringBuffer and StringBuilder in detail in String in java, StringBuffer in java and StringBuilder in java.

1) Convert String to Stream.

Below code example demonstrate simple way to convert String to Stream using method String.getBytes() and InputStream class.

package com.code2succeed.utils;

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

public class StringToStream {
	public static void main(String[] args) throws IOException {
		String str = "code2succeed example";
		
		//convert string to stream 
		InputStream is = new ByteArrayInputStream(str.getBytes());
		
		//code to verify stream data
		InputStreamReader reader = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(reader);
		
		String line = "";
		while((line = br.readLine()) != null) {
			System.out.println(line);
		}
	}
}
Output
code2succeed example

2) Convert Stream to String.

Below code example demonstrate simple way to convert Stream to String. Helper method is used to generate Stream from String however in practical scenario you don’t need to do so as you have stream as input.

package com.code2succeed.utils;

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

public class StreamToString {
	public static void main(String[] args) throws IOException {
		StreamToString streamToString = new StreamToString();
		
		//call helper method to get InputStream
		InputStream is = streamToString.getStream();
		
		//call method to convert Stream to String
		String text = streamToString.getText(is);
		System.out.println(text);
	}
	
	//helper method to get InputStream
	public InputStream getStream() {
		String str = "Code2Succeed example \n"
				+ "for StreamToString";
		
		InputStream is = new ByteArrayInputStream(str.getBytes());
		return is;
	}
	
	//method to convert InputStream to String
	public String getText(InputStream is) throws IOException {
		StringBuilder sb = new StringBuilder();
		InputStreamReader reader = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(reader);
		
		String line = "";
		while((line = br.readLine()) != null) {
			sb.append(line);
		}
		return sb.toString();
	}
}
Output
Code2Succeed example for StreamToString

Stay tuned for more tutorials and examples !!!

Leave a Reply

Your email address will not be published. Required fields are marked *