Search code examples
java-iofileoutputstreambufferedinputstream

How to make a downloader in java


I am making a downloader in java to download small to large files.

My logic to download files is as follows

  URL url=new URL(urlToGetFile);
                int count=-1; //this is for counter
                int offset=0;
                BufferedInputStream bufferedInputStream=new BufferedInputStream(url.openStream()); 
                FileOutputStream fileOutputStream=new FileOutputStream(FinalFilePath);


                byte data[] = new byte[1024];  



                while(  ((count=bufferedInputStream.read(data,0,1024))!=-1) )
                                         {
                        fileOutputStream.write(data,0, 1024);
                         }              
                bufferedInputStream.close();
                fileOutputStream.close();
                PrintLine("File has download");

And it works only for small files but as I download large files these are download but are corrupted.

After reading many questions I am also little bit confused that why everyone is coding fileOutputStream.write(data,0, 1024); to make offset to 0 and same with offset for bufferedInputStream.

I also want to know how to change that offset for BufferedInputStream and for FileOutputStream. While getting bytes in loop.


Solution

  • You need to write the amount that was read.

    When you read into the buffer you can read fewer than 1024 bytes. For example a 1200-byte file would be read as 1024 + 176. Your count variable stores how much was actually read, which would be 176 the second time around your loop.

    The reason for corruption is that you would be writing 176 'good' bytes plus (1024 - 176 = 848) additional bytes that were still in the data array from the previous read.

    So try:

    while( ((count=bufferedInputStream.read(data,0,1024))!=-1) )
    {
        fileOutputStream.write(data,0, count);
    }  
    

    The zero offset in that write call is an offset into data, which you really do want to be zero. See the Javadoc for details. There is no difference for other stream types.