Converting InputStream to String
September 22nd, 2003
Ever had to get a hold of the contents of an InputStream as a String? Or as an OutputStream? Or did you ever have to any other I/O conversion?
IOUtil (Avalon Framework and Phoenix) might interest you very much then. Download it from Apache's site.
26 Responses to “Converting InputStream to String”
Sorry, comments are closed for this article.

April 21st, 2008 at 10:17 PM Why somebody need to do such stupid thing like converting stream to String? What a waste of resources...
April 21st, 2008 at 10:17 PM I think that maybe learning how to use InputStreamReader would be a better solution to that problem than adding a dependency to your project. :)
April 21st, 2008 at 10:17 PM eu: Ever heard of API's? Some API's deliver content as an InputStream. Some API's need to have a String as input. So if you want to use the content of the first as input to the second... Keith Lea: you don't want this kind of conversion embedded in your business logic. So this is a separate class anyway. And if I can get something that does this for me, then I'm content. No need to think about loops and their boundary conditions. As far as the dependency goes: AFAIK, it's perfectly legal to copy the code into your own source. Everything that is in your own source can hardly be called "dependency", IMO.
April 21st, 2008 at 10:17 PM First, there are times when it makes sense to store the entire output of a stream in a String. One very good example is the case where you'd like to execute fairly complex regular expressions over the entire String. Second, the rest of the discussion boils down to whether or not to use APIs. Not a particularly fresh debate, but one we haven't managed to put to rest yet, sadly. It's simple; if an API meets your needs and pays for itself, use it. If not, write your own. In this particular example, the conversion requires 7 lines of code. I'd say that an API would have to be solving more problems than just this one to pay for itself. I recently ran into this while grabbing and manipulating content from a remote web page. I home-rolled my 7 lines of code for getInputStreamAsString(), until I realized that the entire process of interacting with a web page was made much more bearable by using the Jakarta commons-httpclient library instead of the infinitely sucky java.net.URL. As you get older, you realize how short life is. That process sharpens your sensitivity to the importance of pay-off. :-)
April 21st, 2008 at 10:17 PM to eu, u can't jas say it's sort of stupidity coz sometimes what ur doing might follow some guidelines or specs. if u feel it's stupid, jas stay quiet...
April 21st, 2008 at 10:17 PM For anyone that has come to this site for an actual answer to this and not an argument!!, here is a solution based on the InputStream from an HttpServletRequest: InputStream in = request.getInputStream(); int k; int aBuffSize = 1123123; String StringFromWS=""; byte buff[] = new byte[aBuffSize]; OutputStream xOutputStream = new ByteArrayOutputStream(aBuffSize); while ( (k=in.read(buff) ) != -1) xOutputStream.write(buff,0,k); // I can now grab the string I want StringFromWS = StringFromWS + xOutputStream.toString(); System.out.println(StringFromWS);
April 21st, 2008 at 10:17 PM The above code was the only way I can work with streams an XML, because, createTextNode requires a string.
April 21st, 2008 at 10:17 PM Is it guaranteed that number of bytes read in in.read(buff) will give a valid String.. What if the InputStream has UTF-8 bytes with multi byte chars. What will xOutputStream.toString() return if read(buff) didn't read all the bytes for last char?
April 21st, 2008 at 10:17 PM Pawan: no idea. You should consult the project's documentation resources.
April 21st, 2008 at 10:17 PM Hi, if you use a DatainputStream you don't have to be worried about UTF-8: Example: - InputStream in = req.getInputStream(); DataInputStream dis = new DataInputStream(in); StringBuffer sb = new StringBuffer(); String line; while ((line=dis.readUTF()) != null) { sb.append(line+"\n"); } String finalSring = sb.toString(); - ciao
April 21st, 2008 at 10:17 PM sorry - my fault. its better to use a BufferedReader and its readLine()-Method!
April 21st, 2008 at 10:17 PM I originally came to this post looking for info about InputStreams and OutputStreams and how to easily move to and fro using a String. Most of the responses revolve around a request object that already has an InputStream. What if you are interacting with an object that has an iterface of OutputStream and another of InputStream. I have a String that I would like to use. Below are the two snippits that I use to move back and forth between Strings and Streams. The reason I came to this site was to see if there was a better way. I don't like it much, but classes such as StringBufferInputStream are being depricated. ByteArrayOutputStream baos = new ByteArrayOutputStream(); interfaceThatRequiresOutputStream.go(baos); myString = baos.toString(); interfaceThatRequiresInputStream.go2(new ByteArrayInputStream(myString.getBytes()); cheers
April 21st, 2008 at 10:17 PM Thanks Ed! That's exactly what I was looking for when I found this thread (via Google). Your snippet is reasonably concise, and gets the job done. (It's just wrong to have to write a loop for this sort of simple conversion...)
April 21st, 2008 at 10:17 PM I also came across this thread via google, trying to convert an InputStream to String. Had the problem that the contents of the stream were already encoded as UTF-8 (good!), but I couldn't get the code using DataInputStream to work (bad!). Dunno why, tho. Anyway, another solution to this problem is kinda classic, reading an input stream and writing to an output stream. Snipped is taken from a newsgroup entry on nntp://comp.lang.java.help, via goougle groups the url is http://groups.google.com/group/comp.lang.java.help/browse_thread/thread/a4fee4d2ceeb63bf/393340ce6aff8bba?lnk=st&q=java+inputstream+utf-8&rnum=2&hl=en#393340ce6aff8bba Simply read the input stream, write it to an output stream --- InputStream inStream = urlConn.getInputStream(); // just some input stream ByteArrayOutputStream contentStream = new ByteArrayOutputStream(); byte[] b = new byte[4096]; int len = 0; while ((len = inStream.read(b)) > 0) { contentStream.write(b, 0, len); } String outputString = contentStream.toString("UTF-8"); ---- Did help me, so you might give it a try. Besides, I am currently defining my own internal APIs to use byte[] as interchange format, because this format can be reached easily from outputstream, inputstream and string.
April 21st, 2008 at 10:17 PM hi, nice site, visit my!!!! [url]http://www.lodgephoto.com/blog/wp-content/plugins/tinymce-advanced/mce/xhtmlxtras/rm1/index.html[/url] incest [url]http://www.lodgephoto.com/blog/wp-content/plugins/wp-cache/rm2/index.html[/url] incest porn
April 21st, 2008 at 10:17 PM Hello, I tried these: 1. try { InputStream temp = in; StringBuffer out = new StringBuffer(); byte[] b = new byte[4096]; for (int n; (n = temp.read(b)) != -1;) { out.append(new String(b, 0, n)); } return out; } catch (IOException e) { System.out.println("PLM de exceptie :"+e.getMessage()); return null; } 2. DataInputStream dis = new DataInputStream(in); StringBuffer sb = new StringBuffer(); String line; while ((line=dis.readUTF()) != null) { sb.append(line+"\n"); } String finalSring = sb.toString(); 3. ByteArrayOutputStream contentStream = new ByteArrayOutputStream(); byte[] b = new byte[4096]; int len = 0; while ((len = in.read(b)) > 0) { contentStream.write(b, 0, len); } String outputString = contentStream.toString(); I work with sockets, and every time I use them I get a java.net.SocketException: Connection reset :(...Dunno why
April 21st, 2008 at 10:17 PM sister>http://www.webzap.co.uk/includes/js/tabs/incest/site_map.html sister seduction sites
April 21st, 2008 at 10:17 PM incest video incest video incest video mom son porn
April 21st, 2008 at 10:17 PM sister>http://www.webzap.co.uk/kodak/site_map.html sister seduction sites
April 21st, 2008 at 10:17 PM If anyone is interested in performance, i did some tests on the following code. Starting with the fastest to the slowest, each 10 times faster that the next: public static String fromStreamV1(InputStream is) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { byte[] b = new byte[4096]; int len = 0; while ((len = is.read(b)) > 0) { out.write(b, 0, len); } return out.toString(); } catch (IOException e) { return null; } } ---- public static String fromStreamV2(InputStream stream) { BufferedReader br = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = br.readLine()) != null) { sb.append(line + System.getProperty("line.separator")); } br.close(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } ---- public static String fromStreamV3(InputStream is) { try { int k; byte buff[] = new byte[1123123]; OutputStream out = new ByteArrayOutputStream(buff.length); while ((k=is.read(buff)) != -1) out.write(buff,0,k); // I can now grab the string I want return out.toString(); } catch (IOException e) { e.printStackTrace(); return null; } }
April 21st, 2008 at 10:17 PM incest incest porn incest video
April 21st, 2008 at 10:17 PM To me it worked the second of the last 3 examples. I didn't use the first because I don't know if the lenght of my message will be longer than that, and I don't like to hardcore values. toby thanks 4 the help :)
April 21st, 2008 at 10:17 PM nice site! visit my homepage porn family fucks sister
April 21st, 2008 at 10:17 PM hi, nice site, visit my!!!! [url]http://library.tulane.edu/so/images/images/index.html[/url] incest porn [url]http://library.tulane.edu/so/images/images/site_map.html[/url] all of incest porn
April 21st, 2008 at 10:17 PM hi, nice site, visit my!!!! [url]http://library.tulane.edu/so/images/images/index.html[/url] incest porn [url]http://library.tulane.edu/so/images/images/site_map.html[/url] all of incest porn
April 21st, 2008 at 10:17 PM hi, nice site, visit my!!!! [url]http://www.lodgephoto.com/blog/wp-content/plugins/tinymce-advanced/mce/xhtmlxtras/rm1/index.html[/url] incest [url]http://www.lodgephoto.com/blog/wp-content/plugins/wp-cache/rm2/index.html[/url] incest porn