Multi-thread breakpoint download implementation in Java and multi-thread breakpoint download in java

Source: Internet
Author: User

Multi-thread breakpoint download implementation in Java and multi-thread breakpoint download in java

RandomAccessFileClass:
Such instances support reading and writing random access files. Random access to files is similar to a large byte array stored in the file system. There is a pointer to the hidden array, the cursor or index, called a file pointer. The input operation reads bytes from the file pointer and advances the file pointer as the bytes are read. If a random access file is created in read/write mode, the output operation is also available. The output operation starts writing bytes from the file pointer and advances the file pointer as the bytes are written. The output operation after the current end of the hidden array causes the array to expand. The file pointer can be read using the getFilePointer method and set using the seek method.

The following is a demo of RandomAccessFile for breakpoint download in Android.
The server can use tomcat to simulate and put the downloaded test file under the webApp/ROOT directory.
First, we will provide the multi-threaded download code implemented by java using the HttpURLConnection class:

Public class MultiThread {private static int threadCount = 3; private static long blockSize; private static int runningThreadCount; public static void main (String [] args) throws Exception {String path = "http: // 10.0.67.172/test.exe "; URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setConnectTimeout (5000); // timeout int cod E = conn. getResponseCode (); System. out. println (code); if (code/100 = 2) {int size = conn. getContentLength (); // get the length of the resource file System. out. println ("request resource size:" + size); blockSize = size/threadCount; // number of resource files to be divided into. runningThreadCount = threadCount; long startIndex = 0; long endIndex = 0; // enable several sub-threads to download multiple threads for (int I = 0; I <threadCount; I ++) {startIndex = I * blockSize; endIndex = (I + 1) * blockSiz E-1; if (I = threadCount-1) {endIndex = size-1;} System. out. println ("enable thread:" + I + ";" + "start position:" + startIndex + ":" + "end position:" + endIndex); new DownThread (path, startIndex, endIndex, I ). start () ;}} private static class DownThread extends Thread {private String path; private long startIndex; private long endIndex; private int threadId; public DownThread (String path, long startIndex, long endI Ndex, int threadId) {super (); this. path = path; this. startIndex = startIndex; this. endIndex = endIndex; this. threadId = threadId;} @ Override public void run () {try {URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setreadtimeouts (5000); conn. setRequestProperty ("Range", "bytes =" + startIndex + "-" + endIndex); // you can specify Int code = conn. getResponseCode (); if (code/100 = 2) {InputStream is = conn. getInputStream (); File file = new File ("temp.exe"); RandomAccessFile raf = new RandomAccessFile (file, "rw"); raf. seek (startIndex); System. out. println ("Number" + threadId + "file start position:" + String. valueOf (startIndex); int len = 0; byte [] buffer = new byte [1024]; while (len = is. read (buffer ))! =-1) {raf. write (buffer, 0, len); // write File} raf. close () ;}} catch (Exception e) {e. printStackTrace ();}}}}

The principle of resumable download is to save the last object download location as a temporary object and delete it when the download is complete.

Public class MultiThread {private static int threadCount = 3; private static long blockSize; private static int runningThreadCount; public static void main (String [] args) throws Exception {String path = "http: // 10.0.67.172/test.rar "; URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setConnectTimeout (5000); // timeout int cod E = conn. getResponseCode (); System. out. println (code); if (code/100 = 2) {int size = conn. getContentLength (); // get the length of the resource file System. out. println ("request resource size:" + size); blockSize = size/threadCount; // number of resource files to be divided into. runningThreadCount = threadCount; long startIndex = 0; long endIndex = 0; for (int I = 0; I <threadCount; I ++) {startIndex = I * blockSize; endIndex = (I + 1) * blockSize-1; if (I = threa DCount-1) {endIndex = size-1 ;}system. out. println ("enable thread:" + I + ";" + "start position:" + startIndex + ":" + "end position:" + endIndex); new DownThread (path, startIndex, endIndex, I ). start () ;}} private static class DownThread extends Thread {private String path; private long startIndex; private long endIndex; private int threadId; public DownThread (String path, long startIndex, long endIndex, int threadId) {Super (); this. path = path; this. startIndex = startIndex; this. endIndex = endIndex; this. threadId = threadId;} @ Override public void run () {int total = 0; try {File positionFile = new File (threadId + ". txt "); URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); // continue to download if (positionFile. exists () & positionFile. length ()> 0) {FileInputStream FCM = new FileInputStream (positionFile); BufferedReader reader = new BufferedReader (new InputStreamReader (fiis )); // obtain the total size of the last downloaded String lasttotalstr = reader. readLine (); int lastTotal = Integer. valueOf (lasttotalstr); System. out. println ("total size of the last thread download:" + lastTotal); startIndex + = lastTotal; total + = lastTotal; FCM. close ();} conn. setreadtimeouts (5000); conn. setRequestProperty ("Range", "bytes =" + startIndex + "-" + endIndex); // you can specify the int code = conn. getResponseCode (); if (code/100 = 2) {InputStream is = conn. getInputStream (); File file = new File ("temp.rar"); RandomAccessFile raf = new RandomAccessFile (file, "rw"); raf. seek (startIndex); System. out. println ("Number" + threadId + "file start position:" + String. valueOf (startIndex); int len = 0; byte [] buffer = new byte [1024]; w Hile (len = is. read (buffer ))! =-1) {RandomAccessFile rf = new RandomAccessFile (positionFile, "rwd"); raf. write (buffer, 0, len); // write File total + = len; rf. write (String. valueOf (total ). getBytes (); rf. close ();} is. close (); raf. close () ;}} catch (Exception e) {e. printStackTrace ();} finally {synchronized (DownThread. class) {System. out. println ("Thread" + threadId + "downloaded"); runningThreadCount --; if (runningThreadCount <1) {System. out. Println ("All threads are finished. Delete the temporary record File "); for (int I = 0; I <threadCount; I ++) {File f = new File (I + ". txt "); System. out. println (f. delete ());}}}}}}}

Running result:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.