Possible Duplicate:
In Java how do a read/convert an InputStream in to a string?
Hi, I want to convert this BufferedInputStream into my string. How can I do this?
BufferedInputStream in = new BufferedInputStream(sktClient.getInputStream() );
String a= in.read();
Yash Joshi
62711 silver badges28 bronze badges
asked Apr 19, 2011 at 8:52
5 Answers 5
BufferedInputStream in = new BufferedInputStream(sktClient.getInputStream());
byte[] contents = new byte[1024];
int bytesRead = 0;
String strFileContents;
while((bytesRead = in.read(contents)) != -1) {
strFileContents += new String(contents, 0, bytesRead);
}
System.out.print(strFileContents);
answered Apr 19, 2011 at 9:00
Sign up to request clarification or add additional context in comments.
3 Comments
JJ_Coder4Hire
one small bug. in the while loop you should be appending with each iteration. it should be += instead of =. ie: strFileContents += new String(contents, 0, bytesRead);
chacham15
@JJ_Coder4Hire that isnt the only bug, this code relies on chance that the string encoding has a boundary at the bytesRead mark (which is an ok assumption ONLY for ASCII).
WoutVanAertTheBest
I had to put 'System.out.print(strFileContents);' inside loop else only last piece of my html response was shown. btw thanks
With Guava:
new String(ByteStreams.toByteArray(inputStream),Charsets.UTF_8);
With Commons / IO:
IOUtils.toString(inputStream, "UTF-8")
answered Apr 19, 2011 at 9:03
Comments
I suggest you use apache commons IOUtils
String text = IOUtils.toString(sktClient.getInputStream());
answered Apr 19, 2011 at 9:04
Comments
Please following code
Let me know the results
public String convertStreamToString(InputStream is)
throws IOException {
/*
* To convert the InputStream to String we use the
* Reader.read(char[] buffer) method. We iterate until the
35. * Reader return -1 which means there's no more data to
36. * read. We use the StringWriter class to produce the string.
37. */
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try
{
Reader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
}
finally
{
is.close();
}
return writer.toString();
} else {
return "";
}
}
Thanks, Kariyachan
answered Apr 19, 2011 at 8:59
2 Comments
Sean Patrick Floyd
No casting needed. BufferedInputStream is an InputStream
B. Clay Shannon-B. Crow Raven
"Thanks, Kariyachan" I remember that cat from "Man from U.N.C.L.E." - he's a programmer now?
If you don't want to write it all by yourself (and you shouldn't really) - use a library that does that for you.
Apache commons-io does just that.
Use IOUtils.toString(InputStream), or IOUtils.readLines(InputStream) if you want finer control.
answered Apr 19, 2011 at 9:05
Comments
lang-java