- Java Developers faces the requirement for converting String to Stream or vice verse many times during the project development.
- Generally when there is a situation like reading some file from a remote source (HTTP request), Then the response comes in stream.Here developer need to convert this stream to string.
Code For String to Stream or Stream to String:-
package com.sandeep.java.utility;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JavaUtility {
public static InputStream convertStringToStream(String instr) {
InputStream is = new ByteArrayInputStream(instr.getBytes());
return is;
}
public static String convertStreamToString(InputStream is) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder outputstring = new StringBuilder();
String chunk = null;
try {
while ((chunk = br.readLine()) != null) {
outputstring.append(chunk);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return outputstring.toString();
}
public static void main(String[] args) {
InputStream ins = JavaUtility.convertStringToStream("Sandeep Patel- Original input String");
String outputString = JavaUtility.convertStreamToString(ins);
System.out.print("Output : "+outputString+"n");
}
}
Output:-
Output : Sandeep Patel- Original input String