How to ensure I get the picture is complete? (in java)

Posted by Zenofo on Stack Overflow See other posts from Stack Overflow or by Zenofo
Published on 2011-01-13T00:48:25Z Indexed on 2011/01/13 0:53 UTC
Read the original article Hit count: 125

Filed under:

i using below code to get a picture from URL:

    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);

this code is okay,but my internet connect is very very bad,

so ,I maybe get a broken picture like this:

alt text

How can I ensure the picture file is complete ?

I think you can add this code to try and test this:

if (len == -1) { change to if (len == -1 || (int)(Math.random()*100)==1 ) {

full test 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);

thanks for help :)

© Stack Overflow or respective owner

Related posts about java