74

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
0

5 Answers 5

51
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

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);
@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).
I had to put 'System.out.print(strFileContents);' inside loop else only last piece of my html response was shown. btw thanks
37

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

19

I suggest you use apache commons IOUtils

String text = IOUtils.toString(sktClient.getInputStream());
answered Apr 19, 2011 at 9:04

Comments

11

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

No casting needed. BufferedInputStream is an InputStream
"Thanks, Kariyachan" I remember that cat from "Man from U.N.C.L.E." - he's a programmer now?
6

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.