title: Java Read JPG File From URL
body: <pre><code>public class Socket {
      public Socket() {
          try {
              URL url = new URL("http://images2.layoutsparks.com/1/56178/castle-stone-window-grey.jpg");
              InputStream in = url.openStream();
              BufferedInputStream bin = new BufferedInputStream(in); 
  
  
              ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
              byte[] okunan = new byte[4096];
  
              while(in.read()!= -1){
                  bout.write(okunan, 0, in.read());
  
              }
  
          } catch (MalformedURLException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p>I got this error:
  Exception in thread "main" java.lang.IndexOutOfBoundsException
      at java.io.ByteArrayOutputStream.write(Unknown Source)</p>
  
  <p>I want to read this jpeg file to in bytearrayoutputstream after then write to file.</p>
  
  <p>Sory for my bad english..</p>