Implement pause/resume in file downloading

后端 未结 5 1197
小鲜肉
小鲜肉 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:52

    Okay problem fixed, here is my code for other users who wants to implement pause/resume:

            if (outputFileCache.exists())
            {
                connection.setAllowUserInteraction(true);
                connection.setRequestProperty("Range", "bytes=" + outputFileCache.length() + "-");
            }
    
            connection.setConnectTimeout(14000);
            connection.setReadTimeout(20000);
            connection.connect();
    
            if (connection.getResponseCode() / 100 != 2)
                throw new Exception("Invalid response code!");
            else
            {
                String connectionField = connection.getHeaderField("content-range");
    
                if (connectionField != null)
                {
                    String[] connectionRanges = connectionField.substring("bytes=".length()).split("-");
                    downloadedSize = Long.valueOf(connectionRanges[0]);
                }
    
                if (connectionField == null && outputFileCache.exists())
                    outputFileCache.delete();
    
                fileLength = connection.getContentLength() + downloadedSize;
                input = new BufferedInputStream(connection.getInputStream());
                output = new RandomAccessFile(outputFileCache, "rw");
                output.seek(downloadedSize);
    
                byte data[] = new byte[1024];
                int count = 0;
                int __progress = 0;
    
                while ((count = input.read(data, 0, 1024)) != -1 
                        && __progress != 100) 
                {
                    downloadedSize += count;
                    output.write(data, 0, count);
                    __progress = (int) ((downloadedSize * 100) / fileLength);
                }
    
                output.close();
                input.close();
           }
    

提交回复
热议问题