Suppose I have a have java.io.InputStream
object, how should I process that object and produce a
String
from it in java?
I would need a function which reads InputStream and output it as a String
thanks
These are few ways to do it
1. Using InputStreamReader : simple implementation which uses the InputStreamReader to convert from bytes to characters.
private static String inputStreamToString(InputStream in)
throws java.io.IOException
{
BufferedReader br = null;
try {
InputStreamReader isr = new InputStreamReader(in);
br = new BufferedReader(isr);
char cbuf[] = new char[2048];
int len;
StringBuilder sbuf = new StringBuilder();
while ((len = br.read(cbuf, 0, cbuf.length)) != -1)
sbuf.append(cbuf, 0, len);
return sbuf.toString();
} finally {
if ( br != null ) br.close();
}
}
2. Using
Apache commons IOUtils
to copy to copy the
InputStream
into a StringWriter
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
OR Simply
String myString = IOUtils.toString(myInputStream, "UTF-8");
3. using only standard Java library
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
4. Using parallel Stream Api (Java 8
). Warning: This solution convert different line breaks (like
\r\n
) to \n
String result = new BufferedReader(new InputStreamReader(inputStream)).lines()
.parallel().collect(Collectors.joining("\n"));
5. Complete Example :
public static void main(String[] args) throws FileNotFoundException, IOException {
InputStream in = new ByteArrayInputStream("hello".getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader( in ));
String line = null;
StringBuilder out = new StringBuilder();
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString());
reader.close();
}
//output :hello
there are many more other ways, but i have listed mostly used one's, but it all depends on your requirement and your choice
Using Standard java library
static String convertStreamToString(java.io.InputStream inputStr) {
java.util.Scanner s = new java.util.Scanner(inputStr).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
You can also add encoding, in the above code, by passing 'encoding' as second argument of 'Scanner'.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly