Multi-threaded Breakpoint Download principle (Java code example Demo)

Source: Internet
Author: User

In fact, multi-threaded breakpoint Download principle, very simple, then we come to understand, how to achieve multi-threaded breakpoint Download, first: You must understand the 1th, then is, what is multi-threaded download, the knowledge point can view this blog on an article, Android multi-Threading Download principle, breakpoint download it, In fact, this is based on the addition of some things, then add something, now to do a detailed understanding.

1. In the process of downloading, the side downloads, changes a file to record the location of the download, that is, the number of downloaded data

1. Create a file

2. Record how much data is downloaded

3. Storing data

2. When the second download, read the file to see if the data, read the location of the last download, as the beginning of the download location

1. Create a File object

2. Check if there is any data in the files and files

3. Read the data and take the data to the starting position, that is, starting from this data download

3. After the file download is complete, delete the recorded files, be sure to download the file after the deletion, or you will jump out of some exceptions, for example, this time the file is gone, you need to restart the download and so on

4. The above said that this is not a little bit of understanding, then the following to see the real practice it


Package Com.zengtao.demo;


Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.InputStream;
Import Java.io.RandomAccessFile;
Import java.net.HttpURLConnection;
Import Java.net.URL;


/**
* File Downloader
*
* @author Administrator Zengtao
*
*/
public class Demoloader {
private static Demoloader loader = new Demoloader ();
private static int threadcount = 3;
private static int runningthread = 3;


Private Demoloader () {


}


public static Demoloader getinstance () {
return loader;
}


/**
* Go to server-side download file
*
* @param path
* Server Address
*/
public void Downfile (String path) {
Go to the server side to get the length of the file, create a local file with the same size as the server
try {
URL url = new URL (path);
HttpURLConnection connection = (httpurlconnection) URL
. OpenConnection ();
Connection.setdoinput (TRUE);
Connection.setrequestmethod ("GET");
Connection.setreadtimeout (5000);
int code = Connection.getresponsecode ();
if (code = = 200) {
1. Get the length of the server-side file
int filelength = Connection.getcontentlength ();
2. Create a local file with the same size as the server
Randomaccessfile RAF = new Randomaccessfile ("Setup.exe", "RWD");
Raf.setlength (filelength);
Raf.close ();
3. Suppose three threads are downloaded
int blockSize = Filelength/threadcount;
for (int threadId = 0; threadId < threadcount; threadid++) {
int startIndex = (threadId-1) * blockSize;
int endIndex = threadId * BLOCKSIZE-1;
if (threadId = = ThreadCount) {
EndIndex = Filelength;
}


Log hypothesis Download
SYSTEM.OUT.PRINTLN ("assumed thread:" + threadId + ", download:" + StartIndex
+ "--->" + endIndex);
4. Start the download
New Downloadthread (ThreadId, StartIndex, EndIndex, Path)
. Start ();
}
SYSTEM.OUT.PRINTLN ("Total file length:" + filelength);
} else {
SYSTEM.OUT.PRINTLN ("Request failed! ");
}


} catch (Exception e) {
E.printstacktrace ();
}
}


/**
* Download the file thread
*
* @author Administrator Zengtao
*
*/
public class Downloadthread extends Thread {
private int threadId;
private int startIndex;
private int endIndex;
Private String path;


/**
*
* @param threadId
* Thread ID
* @param startIndex
* Thread Download Start location
* @param endIndex
* Thread Download End location
* @param path
* Thread download end file drop address
*/
Public downloadthread (int threadId, int startIndex, int endIndex,
String path) {
Super ();
This.threadid = threadId;
This.startindex = StartIndex;
This.endindex = EndIndex;
This.path = path;
}


@Override
public void Run () {
Super.run ();
try {
1. Check if there is a record-------------------------------------------------------------------------------------------------
File File = new file (threadId + ". txt");
if (file.exists () && file.length () > 0) {
FileInputStream fis = new FileInputStream (file);
byte[] temp = new byte[1024];
int leng = fis.read (temp);
String loadlength = new String (temp, 0, Leng);
int load = Integer.parseint (loadlength);
StartIndex = load;
Fis.close ();
}
URL url = new URL (path);
HttpURLConnection connection = (httpurlconnection) URL
. OpenConnection ();
2. Request the server download part of the file, set the start location, and end location
Connection.setrequestproperty ("Range", "bytes=" + startIndex
+ "-" + EndIndex);
Log Real Download
SYSTEM.OUT.PRINTLN ("Real thread:" + threadId + ", download:" + StartIndex
+ "--->" + endIndex);
Connection.setdoinput (TRUE);
Connection.setrequestmethod ("GET");
Connection.setreadtimeout (5000);
3. All data obtained from the server, return: 200, get some data from the server, return: 206
int code = Connection.getresponsecode ();
SYSTEM.OUT.PRINTLN ("code =" + code);
InputStream is = Connection.getinputstream ();
Randomaccessfile RAF = new Randomaccessfile ("Setup.exe", "RWD");
Raf.seek (StartIndex); When the file is randomly written, when does it start?
int len = 0;
int total = 0; Record how many downloads-----------------------------------------
byte[] buff = new byte[1024];
while (len = is.read (buff))! =-1) {
Randomaccessfile info = new Randomaccessfile (threadId
+ ". txt", "RWD");
Raf.write (buff, 0, Len);
Total + = Len;
Info.write ("" + StartIndex + total). GetBytes ()); 4. Save data: (real download to the beginning of the location) downloaded + start----------------------------------------
Info.close ();
}
Is.close ();
Raf.close ();
System.out.println ("Thread:" + threadId + ", download Complete");
} catch (Exception e) {
E.printstacktrace ();
} finally {
5.notice Make sure the files are downloaded before deleting the log files
runningthread--;
if (Runningthread = = 0) {
for (int i = 1; I <= threadcount; i++) {
File File = new file (i + ". txt");
File.delete ();
}
System.out.println ("File download complete, delete record file"); ---------------------------------------------------------------------
}
}
}
}
}

Multi-threaded Breakpoint Download principle (Java code example Demo)

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.