One, multithreading download
Multi-threaded download is to preempt server resources
Principle: The server CPU allocated to each thread of the same time slice, the server bandwidth evenly allocated to each thread, so the more threads the client opens, you can preempt more server resources.
1, set the number of open threads, send HTTP request to download the address, get the total length of the download file
Then create a consistent length of temporary files, avoid downloading to half of the storage space, and calculate how much data each thread downloads
2. Calculate the start and end position of each thread download data
Send the request again, using the Range header to request the start and end position data
3, the download to the data, storage to the temporary file
4, with a breakpoint continued to download the multithread
Define an int variable, record the total length of the data downloaded by each thread, and then add the thread's download start position, the result is the next download, the thread's start position, the resulting results into the cached file, when the file download complete, delete the temporary progress file.
public class Multidownload {static int threadcount =;
static int finishedthread =;
OK download address static String filename = "EditPlus.exe";
static String Path = "http://...:/" +filename;
public static void Main (string[] args) {//, send a GET request to obtain the length of the download file a try {URL url = new URL (path);
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Conn.setrequestmethod ("get");
Conn.setconnecttimeout ();
Conn.setreadtimeout ();
if (conn.getresponsecode () = =) {//If the request succeeds, get the length of the requested resource file, int length = Conn.getcontentlength (); , generate a temporary file of the same size as the original file, so as not to download half of the storage space is not enough file File = new file (filename);//demo, so will save the file directory in the project with the same directory//use RANDOMACC Essfile generates temporary files that can be positioned anywhere in the file with pointers,//and can be written to the hardware underlying device in real time, skipping over the cache, which is good for unexpected outages such as downloading files Randomaccessfile RAF = new Rand
Omaccessfile (file, "RWD");//rwd, real-time write to the underlying device/set the size of the temporary file raf.setlength (length);
Raf.close (); , calculate each threadHow many bytes should be downloaded int size = length/threadcount;//If there are more than one, the last part of the thread is responsible for smashing//opening multithreading for (int threadId =; th Readid < ThreadCount; threadid++) {//calculates the start and end position of each thread download int startIndex = threadid*size;//start = thread ID * size in T endindex = (threadid+) *size-;
End = (thread ID +) *size-//If it is the last thread, then the end position is written dead to the end of the file if (threadId = = ThreadCount-) {
Endindex = length-;
The download interval for//system.out.println ("thread" +threadid+ "is:" +startindex+ "----" +endindex);
New Downloadthread (Startindex,endindex,threadid). Start ();
A catch (Malformedurlexception e) {e.printstacktrace ());
catch (IOException e) {e.printstacktrace ();
{}} class Downloadthread extends thread{private int startIndex;
private int endindex;
private int threadId;
Public downloadthread (int startIndex, int endindex, int threadId) {super (); This.startindex = StartIndex;
This.endindex = Endindex;
This.threadid = threadId; public void Run () {//each thread sends the HTTP request again, downloading its corresponding part of the data try {File progressfile = new File (threadid+). Tx
T "); Determine if the progress file exists, and if so, then the breakpoint continues downloading, if it does not exist, download the IF (Progressfile.exists ()) {FileInputStream FIS = new FILEINPUTST
Ream (Progressfile);
BufferedReader br = new BufferedReader (new InputStreamReader (FIS));
Remove the total progress from the last download from the progress file, then add the original progress to the start and get the new start progress StartIndex + = Integer.parseint (Br.readline ());
Fis.close ();
The download interval for System.out.println ("thread" +threadid+ "is:" +startindex+ "----" +endindex);
, each thread sends the HTTP request its own data URL url = new URL (multidownload.path);
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Conn.setrequestmethod ("get");
Conn.setconnecttimeout ();
Conn.setreadtimeout (); Sets the interval conn.setrequestproperty for the data requested by this HTTP request ("Range", "bytes=" +startindex+ "-" +endindex);
Request part of the data, the response code is if (conn.getresponsecode () = =) {//At this time, the stream only threadcount one of the original file data InputStream I
s = Conn.getinputstream ();
Byte[] B = new byte[];
int len =;
int total =;//total is used to hold breakpoints for continuation of breakpoints//The output stream of the temporary file = new file (multidownload.filename);
Randomaccessfile RAF = new Randomaccessfile (file, "RWD");
Move the write location of the file to StartIndex Raf.seek (StartIndex);
while (len = Is.read (b))!=-{//Every time the data in the stream is read, the data is synchronously written to the temporary file Raf.write (b, Len);
Total = Len;
SYSTEM.OUT.PRINTLN ("thread" + threadId + "Download" + total);
Generates a temporary file that is designed to record download progress Randomaccessfile Progressraf = new Randomaccessfile (Progressfile, "RWD");
Progressraf.write ((total+ ""). GetBytes ());
Progressraf.close ();
} System.out.println ("Thread" +threadid+ "finished downloading---------------------");
Raf.close ();
When all threads have been downloaded, the progress file is deleted multidownload.finishedthread++;
Synchronized (Multidownload.path) {//All threads use the same lock if (Multidownload.finishedthread==multidownload.threadcount) {
for (int i =; i < Multidownload.threadcount; i++) {File F = new file (i+ ". txt");
F.delete ();
} multidownload.finishedthread=;
catch (Exception e) {e.printstacktrace ()}}}; }
}
}
Second, Android mobile phone version with a continuous transmission of multiple-threaded download
The Android phone version of the multi-threaded download with a breakpoint on the same PC version of the same logic, but in the Android phone time-consuming operation can not be placed in the main thread, the network download is time-consuming operation, so multithreading download to open a child in Android thread execution. and use the Message Queuing mechanism to refresh the text progress bar.
public class Mainactivity extends activity {static int threadcount =;
static int finishedthread =;
int currentprogess;
static String Filename = "QQPlayer.exe";
static String Path = "http://...:/" +filename;
Static Mainactivity Ma;
Static ProgressBar PB;
Static TextView TV; static Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {tv.settext (long) PB.G
Etprogress () */pb.getmax () + "%");
};
};
protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Ma = this;
PB = (ProgressBar) Findviewbyid (R.ID.PB);
TV = (TextView) Findviewbyid (r.id.tv);
public void Download (View v) {Thread t = new Thread () {public void run () {///Send HTTP request to get file length, create temporary file
try {URL url= new URL (Path);
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Conn.setrequestmethod ("get"); Conn.setconnecttimeout ();
Conn.setreadtimeout ();
if (conn.getresponsecode () = =) {int length = Conn.getcontentlength ();
The maximum value of the set progress bar is the total length of the original file Pb.setmax (length);
Generates a temporary file of the same size as the original file: File File = new file (Environment.getexternalstoragedirectory (), Filename);
Randomaccessfile RAF = new Randomaccessfile (file, "RWD");
Raf.setlength (length);
Raf.close ();
Calculate the size of the data that each thread needs to download int size = Length/threadcount; Turn on multithreading for (int threadId =; threadId < threadcount; threadid++) {int startIndex = ThreadId
*size;
int endindex = (threadId +) *size-;
if (Threadid==threadcount-) {endindex = length-;
New Downloadthread (StartIndex, Endindex, ThreadId). Start ();
A catch (Exception e) {e.printstacktrace ()); }
}
};
T.start ();
Class Downloadthread extends thread{private int startIndex;
private int endindex;
private int threadId;
Public downloadthread (int startIndex, int endindex, int threadId) {super ();
This.startindex = StartIndex;
This.endindex = Endindex;
This.threadid = threadId; The public void Run () {//each thread sends HTTP requests its own data try{//////////////////First to determine if the breakpoint continues file Progessfile = new file (E
Nvironment.getexternalstoragedirectory (), threadid+ ". txt");
if (progessfile.exists ()) {FileReader FR = new FileReader (progessfile);
BufferedReader br = new BufferedReader (FR);
int lastprogess = Integer.parseint (Br.readline ());
StartIndex + = lastprogess;
Show the progress of the last download to the progress bar currentprogess +=lastprogess;
Pb.setprogress (currentprogess);
Send a message, let the main thread refresh the text progress Handler.sendemptymessage ();
Br.close ();
Fr.close (); URL url = new URL (Path);
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Conn.setrequestmethod ("get");
Conn.setconnecttimeout ();
Conn.setreadtimeout ();
Conn.setrequestproperty ("Range", "bytes=" +startindex+ "-" +endindex);
if (conn.getresponsecode () = =) {InputStream is = Conn.getinputstream ();
byte[] buffer = new byte[];
int len =;
int total =;
File File = new file (Environment.getexternalstoragedirectory (), Filename);
Randomaccessfile RAF = new Randomaccessfile (file, "RWD");
Raf.seek (StartIndex);
while (len = is.read (buffer))!=-) {raf.write (buffer, Len);
Total = Len;
Every time the data in the stream is read, the length of the read data is displayed to the progress bar currentprogess = Len;
Pb.setprogress (currentprogess);
Send a message, let the main thread refresh the text progress Handler.sendemptymessage (); Generate temporary files save download progress for breakpoint Continuation, delete temporary text after all threads are now completePieces of randomaccessfile Progressraf = new Randomaccessfile (Progessfile, "RWD");
Progressraf.write ((total+ ""). GetBytes ());
Progressraf.close ();
} raf.close ();
SYSTEM.OUT.PRINTLN ("Thread" +threadid+ "finished downloading");
When all threads are down, delete the temporary progress file finishedthread++; Synchronized (Path) {if (Finishedthread==threadcount) {for (int i =; i < threadcount; i++)
{File F = new file (Environment.getexternalstoragedirectory (), i+ ". txt");
F.delete ();
} finishedthread=;
catch (Exception e) {e.printstacktrace ()}}}; }
}
}
}
The above content is small to share with you the PC version and Android mobile phone version with breakpoints continued to download the multithread, I hope you like.