RandomAccessFile: resumable upload and multi‑thread multipart download of large files,
How can I resume resumable data transfer?
Use RandomAccessFile. seek
How does one multipart download a single file?
The total length of the file is obtained. The length is divided into N threads for separate download.
1. resumable Data Transfer Using RandomAccessFile:
Key code:
URL url = new URL (threadInfo. getUrl (); connection = (HttpURLConnection) url. openConnection (); connection. setConnectTimeout (5000); connection. setRequestMethod ("GET"); int start = threadInfo. getStart () + threadInfo. getFinished (); // set the range of connection. setRequestProperty ("Range", "bytes =" + start + "-" + threadInfo. getEnd (); // set the File write location file = new File (DownLoadService. DOWNLOAD_PATH, fileInfo. getFileName (); randomAccessFile = new RandomAccessFile (file, "rwd"); randomAccessFile. seek (start); // accumulate currentProgress + = threadInfo. getFinished ();
The two important methods in the Code are:
// Set the start and end ranges. After each pause, download the connection from the previous progress. setRequestProperty ("Range", "bytes =" + start + "-" + threadInfo. getEnd ());
And
// Download randomAccessFile. seek (start) from a specified location );
2. multi‑thread multipart download of large files:
Key code:
// Number of threads private int mThreadCount = 3; // The total length of the downloaded file private int length; // multithreading download // obtain the download length of each thread int childLength = length/mThreadCount; // thread 1: 0, childLength // thread 2: childLength, childLength * 2 // thread 3: childLength * 2, childLength * 3 int start = childLength * I; int end = (I + 1) * childLength-1; for (int I = 0; I <mThreadCount; I ++) {ThreadInfo threadInfo = new ThreadInfo (I, fileInfo. getUrl (), start, end, fileInfo. getFinished (); // if (I = mThreadCount-1) {threadInfo. setEnd (fileInfo. getLength ();} // directly enable the thread in the loop to download DownloadThread downloadThread = new DownloadThread (threadInfo); downloadThread. start () ;}// entity class public class ThreadInfo implements Serializable {public static final String THREAD_INFO = "thread_info"; private int id; // download URL private String url; // download start Node private int start; // download end Node private int end; // current completion progress private int finished; public ThreadInfo (int id, String url, int start, int end, int finished) {this. id = id; this. url = url; this. start = start; this. end = end; this. finished = finished ;}