How to ensure I get the picture is complete? (in java)
<p>i using below code to get a picture from URL:</p>

<pre><code>    URL url=new URL("http://www.google.com/images/logos/ps_logo2.png");
    InputStream in=url.openStream();
    ByteArrayOutputStream tmpOut = new ByteArrayOutputStream();
    byte[] buf = new byte[512];
    int len;
    while (true) {
        len = in.read(buf);
        if (len == -1) {
            break;
        }
        tmpOut.write(buf, 0, len);
    }
    tmpOut.close();

    byte[] picture=tmpOut.toByteArray();
    System.out.println(picture.length);
</code></pre>

<p>this code is okay,but my internet connect is very very bad,</p>

<p>so ,I maybe get a broken picture like this:</p>

<p><img src="http://i.stack.imgur.com/uOk7l.png" alt="alt text"></p>

<p>How can I ensure the picture file is complete ?</p>

<p>I think you can add this code to try and test this:</p>

<p><code>if (len == -1) {</code> change to <code>if (len == -1 || (int)(Math.random()*100)==1 ) {</code></p>

<p>full test code:</p>

<pre><code>    URL url=new URL("http://www.google.com/images/logos/ps_logo2.png");
    InputStream in=url.openStream();
    ByteArrayOutputStream tmpOut = new ByteArrayOutputStream();
    byte[] buf = new byte[512];
    int len;
    while (true) {
        len = in.read(buf);
        if (len == -1 || (int)(Math.random()*100)==1 ) {
            break;
        }
        tmpOut.write(buf, 0, len);
    }
    tmpOut.close();
    byte[] picture =tmpOut.toByteArray();
    System.out.println(picture.length);
</code></pre>

<p>thanks for help :)</p>
