title: How To Convert InputStream To String To Byte Array In Java?
body: <p>On my java server I get from an iOS client an InputStream, which looks like this:</p>
  
  <pre><code>--0xKhTmLbOuNdArY
  Content-Disposition: form-data; filename="Image001"
  Content-Type: image/png
  
  âPNG
  IHDR���@���@���™iqﬁ���gAMA��Ø»7äÈ���tEXtSoftware�Adobe ImageReadyq…e&lt;��IDATx⁄‰;iê]Uôﬂπ˜Ω◊Ø;ΩB::õY
  ê6LÄ“Õ¿
  ... etc. ...
  ≠Yy&lt;‘_˜øüYmc˚æØ…ægﬂóÏK$å±çe0ˆΩleIë¢êH¢Tñê–Üd
  ≠≤§àä6D¸&gt;˙÷˜˚&lt;øÁ˘˝˜˚º^sÁ=Áû{ÓπÁ‹œπ˜úÄÎ:!44¡@
  --0xKhTmLbOuNdArY--
  </code></pre>
  
  <p>The first and last line are my HTTP Boundary. In line 2 and 3 are Information about the image file. And from line 5 until the penultimate line there is the image file which I need as a byte array.</p>
  
  <p><strong>So how do I get the image information as a String and the image file as a byte array from the InputStream?</strong>
  The solution should be fast and efficient (The file size can be several megabytes / &lt; 10 MB ).</p>
  
  <p><em>My approach:</em></p>
  
  <p>I convert the InputStream to a String, then split it and convert the second String to byte array...</p>
  
  <pre><code>String str = org.apache.commons.io.IOUtils.toString( inputStream );
  String[] strArray1 = str.split( "\r\n\r\n", 2 );
  byte[] bytes = strArray1[1].getBytes();
  </code></pre>
  
  <p>That way is very fast, but the byte array seems to be damaged. I can not create an image file from that byte array... Some characters are incorrectly converted.</p>
  
  <p>Perhaps someone can help?</p>