This snippet reads all of the InputStream into a String. Useful for any kind of InputStream, including the content of a HttpResponse after a HttpClient request. See also this answer on SO. Essentially StringBuilder
is a lot faster, and can be converted to a normal String
with the .toString()
method.
For reading the content of a HttpResponse use inputStreamToString(response.getEntity().getContent())
.
// Fast Implementation
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total;
}
// Slow Implementation
private String inputStreamToString(InputStream is) {
String s = "";
String line = "";
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) { s += line; }
// Return full string
return s;
}
6 Comments
You can also use the EasyHttpClient for downloading Web-URLs as a String.
EasyHttpClient must be a 3rd-party lib? It's not being recognized via a simple copy-and-paste...
hello there and thank you for your info - I have definitely picked up something new from proper here. I did on the other hand expertise several technical points the use of this web site, since I skilled to reload the web site a lot of times prior to I may just get it to load correctly. I have been puzzling over if your web host is OK? Now not that I'm complaining, but slow loading circumstances occasions will sometimes have an effect on your placement in google and can injury your quality rating if advertising and advertising with Adwords. Well I'm adding this RSS to my email and can glance out for much extra of your respective exciting content. Make sure you update this again soon.. Kedarnath Badrinath Tour
Actually, you have a very very minor issue in this solution. Your read 'line' is outside the loop.
String is immutable. As we all know. In any case, you wont be reading anything larger that 128K in this kind of solution. (This is still the maximum size of a String, right?...or is it larger now?). But just because (and only 'just because') String is immutable, you might want to do the following just to allow a bit of garbage collection within the loop (although it really doesn't matter) And who knows, GC may never occur within this time anyway:
Enjoy.
Oh...and if you want to retain your line endings, be sure to do
Don't forget!
Re: String length...sorry, I was thinking of something else. Perhaps there is only an MAX_INT limit.
So if you are going to read a 200MB text file with this loop, you really might want to consider allow some GC.