When we download a file from the Internet, some files are relatively large, such as music or video files. It takes a long time to download the file. During the download process, if the current download is interrupted due to a lack of power or other reasons, follow the general program and the next download needs to start again. Here we will implement multi-pure-process breakpoint download, when the download is interrupted, it will be downloaded again next time, a bit like our thunder ......
First, we will not rush to build an Android Application. First, we will build a Java project to test
Create a test case in this project.
You can leave the package empty, because it is only a test, not a real application, so you are lazy ......
OK, then write the code
Package junit. test;Import java. io. ByteArrayOutputStream;
Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. InputStream;
Import java.net. HttpURLConnection;
Import java.net. URL;
Import org. junit. Test;
Public class InternetTest {
/**
* Read the input stream and return data
* @ Param input
* @ Return
* @ Throws Exception
*/
Public byte [] readStream (InputStream input) throws Exception {
Byte [] buffer = new byte [1024];
ByteArrayOutputStream output = new ByteArrayOutputStream ();
Int len =-1;
While (len = input. read (buffer ))! =-1 ){
Output. write (buffer, 0, len );
}
Input. close ();
Output. close ();
Return output. toByteArray ();
}
/**
* Download images from the network
* @ Throws Exception
*/
@ Test
Public void getImage () throws Exception {
String urlPath = "http://photocdn.sohu.com/20110401/Img280097999.jpg"; // link to an image on the network
URL url = new URL (urlPath );
HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // return a connection object
Conn. setRequestMethod ("GET"); // sets the Request Method
Conn. setConnectTimeout (6*1000); // set the connection timeout. You do not need to set it here, but you should set the timeout in android applications.
If (conn. getResponseCode () = 200 ){
InputStream input = conn. getInputStream ();
Byte [] data = readStream (input );
File file =