Search code examples
javaiodownloadbufferedinputstream

Downloading with BufferInputStream not working properly


The following code doesn't work to download a file (btw clen is file's length):

    int pos = 0, total_pos = 0;
    byte[] buffer = new byte[BUFFER_SIZE];
            while (pos != -1) {
                pos = in.read(buffer, 0, BUFFER_SIZE);
                total_pos += pos;
                out.write(buffer);
                setProgress((int) (total_pos * 100 / clen));
            }

...but this works fine:

    int buf;
    while ((buf = in.read()) != -1)
        out.write(buf);

I'm wondering why, even though the second code segment works quickly. On that note, is there any particular reason to use a byte[] buffer (since it doesn't seem to be faster, and BufferedInputStream already uses a buffer of its own....?)


Solution

  • Here's how it should be done.

    public static void copyStream(InputStream is, OutputStream os)
        {
            byte[] buff = new byte[4096];
            int count;
            try {
                while((count = is.read(buff)) > 0)
                    os.write(buff, 0, count);
    
            }catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if(is != null)
                        is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if(os != null)
                        os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
        }