1

I am not able to download large files from the net ( more than 1 mb file ). However, my program is able to download those large files from the localhost. Is there anything else that i need to do to download large files? Here is the code snippet:

 try {

        //connection to the remote object referred to by the URL.
        url = new URL(urlPath);
        // connection to the Server
        conn = (HttpURLConnection) url.openConnection();

        // get the input stream from conn
        in = new BufferedInputStream(conn.getInputStream());

        // save the contents to a file
        raf = new RandomAccessFile("output","rw");


        byte[] buf = new byte[ BUFFER_SIZE ];
        int read;

        while( ((read = in.read(buf,0,BUFFER_SIZE)) != -1) )
    {

            raf.write(buf,0,BUFFER_SIZE);
    }

    } catch ( IOException e ) {

    }
    finally {

    }

Thanks in advance.

Eric Wilson
  • 57,719
  • 77
  • 200
  • 270
rabishah
  • 561
  • 2
  • 4
  • 16

1 Answers1

3

You're ignoring how many bytes you've actually read:

while( ((read = in.read(buf,0,BUFFER_SIZE)) != -1) )
{
    raf.write(buf,0,BUFFER_SIZE);
}

Your write call always writes the whole buffer, even if you didn't fill it with the read call. You want:

while ((read = in.read(buf, 0, BUFFER_SIZE)) != -1)
{
    raf.write(buf, 0, read);
}
Eric Wilson
  • 57,719
  • 77
  • 200
  • 270
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194