Implement pause/resume in file downloading

后端 未结 5 1196
小鲜肉
小鲜肉 2020-12-02 08:12

I\'m trying to implement pause/resume in my download manager, I search the web and read several articles and change my code according them but resume seems not working corre

5条回答
  •  清歌不尽
    2020-12-02 08:38

    It nay be that your server is taking to long to respond (more then the timeout limit) or this is also a fact that not all servers support pause - resume. It is also a point to ponder that weather the file is downloaded through Http, https, ftp or udp.

    Pausing" could just mean reading some of the stream and writing it to disk. When resuming you would have to use the headers to specify what is left to download.

    you may try something like :

     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        if(ISSUE_DOWNLOAD_STATUS.intValue()==ECMConstant.ECM_DOWNLOADING){
             File file=new File(DESTINATION_PATH);
            if(file.exists()){
                 downloaded = (int) file.length();
             connection.setRequestProperty("Range", "bytes="+(file.length())+"-");
        }
    }else{
        connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
    }
    connection.setDoInput(true);
    connection.setDoOutput(true);
    progressBar.setMax(connection.getContentLength());
     in = new BufferedInputStream(connection.getInputStream());
     fos=(downloaded==0)? new FileOutputStream(DESTINATION_PATH): new FileOutputStream(DESTINATION_PATH,true);
     bout = new BufferedOutputStream(fos, 1024);
    byte[] data = new byte[1024];
    int x = 0;
    while ((x = in.read(data, 0, 1024)) >= 0) {
        bout.write(data, 0, x);
         downloaded += x;
         progressBar.setProgress(downloaded);
    }
    

    and please try to sync things.

提交回复
热议问题