Due to the rise of the Linux operating system and the increasing maturity of Java languages, use Java language to implement a cross-platform, and the unique download tool software has become possible. Network ant is a very well known download tool software, I use the Java language to implement software JANTS similar to the basic functions of network ants. This article describes some technical implementation points.
Get a single thread directly network files
The key point of the single thread directly obtains the network file is to obtain the network file to determine the correctness of the basic method. Its initial code is relatively simple, and it can be designed with the basic knowledge of HTTP. Its basic principle is: Connect the network address, open the connection and get the input stream, read data from the input stream. Implement code (used during testing) is as follows:
INT data; // Get data from the input stream
URL URL = New URL ("http://www.sohu.com");
// Create an address of the connection
HTTPURLCONNECTION CONNECTION = Url.openConnection ();
// Open connection
Int responscode = connection. getResponsecode ();
/ / Return to HTTP Response Status Code
InputStream INPUT = Connection.getInputStream ();
// Get input stream
System.out.println ("Responsecode: response);
While ((Data = INPUT.READ ())! = - 1)
System.out.println (DATA);
// Play the obtained data to the screen display
Single-line program break
Everyone often has this experience: suddenly disconnecting the line when a dozens of megabytes is downloaded, and the result is before. You can use breakpoints to solve this problem. Basic principle Here mainly introduces the principle of breakpoint resume. The principle of resume transmission is simple, just different from the HTTP request and the general download. The so-called breakpoint continues to continue downloading from the place where the file has been downloaded. Therefore, when the client passes the web server, add more information - downloaded the starting position, and the HTTP status code returned by the server is also converted from 200 to 206. The above points, you can use the SetRequestProperty () method in the HTTPURLConnection class in the Java language. Key Steps for Renewal of Breppoints 1. Implement the starting position of the submit breakpoint to the starting position of Java provides this feature, the code is as follows:
URL URL = New URL ("http://www.mydomain.com/down.zip";);
HTTPURLCONNECTION httpConnection = (httpurlconnection) URL.OpenConnection ();
/ / Set the start position of the breakpoint resume
HttpConnection.seueStProperty ("Range", "Bytes = 10000");
// Set request information
HttpConnection.setrEquestProperty ("get", "/ down.zip http / 1.1");
// Set the acceptance information
HTTPConnection.seueStProperty ("Accept", "Image / GIF, Image / X-Xbitmap, Application /
MSWORD, * / * ");
// Set connection information
HttpConnection.seueStProperty ("Connection", "Keep-Alive");
// Get the input stream
InputStream INPUT = httpConnection.getinputStream (); from the byte stream removed from the input stream, the Down.zip file starts from the byte stream from 10,000 bytes. 2. Save the obtained byte stream to the file Due to the download of the file involves breakpoint, when saving the file, you need to randomly read and write files. Especially during multi-threaded downloads, you need to locate in the file before writing files. The RandomaccessFile class in the Java IO package can meet this design demand. When the class is positioned in the file, the method used is SEEK (long). The operation is quite simple. Suppose the file is stored from the 10,000-byte, the code is as follows: randomaccess OsavedFile = New RandomaccessFile ("Down.zip", "RW");
// Create a random file
Long npos = 10000;
// Position file pointer to NPOS location
Osavedfile.seek (NPOS);
Byte [] b = new byte [1024];
Int nread;
// Read the byte stream from the input stream, then write to the file
While ((NREAD = INPUT.READ (B, 0, 1024))> 0)
{// INPUT is a stream of network
Osavedfile.write (B, 0, NREAD);
} 3. Save the length value of the downloaded files Since the length of the downloaded file is saved, it should be saved to the file media every time you disconnect. This is the method of object serialization - sequence sequence to be saved into a temporary file. code show as below:
Long nStart;
// Record the number of bytes that have been downloaded
File Tempfile = New File ("donwzip.tmp");
// Create a temporary file
FileOutputStream File = New FileoutputStream (TempFile);
// Create a file output stream
ObjectOutputStream Serialize = New ObjectOutputStream (file);
// Create a file serialization
Serialize.writeObject (nStart); // Serialization
Serialize.flush ();
// Refresh the serialization flow
File.Close ();
// Turn off file output stream
Serialize.close ();
// Close the serialization
Multi-threaded breakpoint resume
After adding breakpoints, the download speed has not yet been improved. In order to prevent the loss of downloaded file data, it is also possible to add multithreading in it to improve the download speed of the network file. Although the first two steps have been basically realized, it seems to be easier to add multiple threads, but not this. During multi-threaded programming, you need to take into account synchronization and mutual exclusion of threads. Since it is a multi-thread to perform breakpoint, consider recording multiple breakpoint positions and record the problem of synchronous mutual exclusion when the breakpoint position is recorded. All of this makes this step more complicated. Synchronous considerations The basic idea of synchronization is to avoid problems when multiple threads access the same resource. Since the multi-thread reads and writes the same file resource, in order to avoid errors, read and write control - is synchronized. The synchronization between the thread is used in Java using Synchronized. Java is an object-oriented language that is manifested in the form of an object. Therefore, the role of the Java synchronization mechanism is to try to avoid access conflicts against "objects". Marking the method or code segment that needs to be synchronized to achieve synchronization, you need to use the keyword synchronized. The system uses the synchronized keyword declaration to set special tags for it. This marker functions as a signal amount, whenever the method is called, the Java's running system will check to confirm the state of this tag, see if the corresponding code has been called executed. If not, the system will grant this internal tag to call the code, after the method runs, the tag is released. Any other object may not be called before the tag is released. The main synchronization code is as follows (use when downloading the data saved into the file): public synchronized int Write (byte [] b, int nstart, int LEN) {
INT n = -1;
Try {
Rf.write (B, NStart, Len);
// Call another class, write data to the file
N = LEN;
} catch (ioexception ie) {
IoE.PrintStackTrace ();
}
Return n;
} When saving the number of downloaded bytes, since multiple breakpoint locations are recorded in different threads, they must be saved at all threads. To this end, the solution is to open a thread that continuously monitors all threads have ended. If the end, save all breakpoints; otherwise, continue to monitor. Similarly, in the thread downloaded by the file, you need to set the flag bit to record whether the thread ends. The basic code is as follows (used in the monitoring thread):
STOP = false;
While (! stop) {
IF (utility.bstop [0] && utility.bstop [1] && utility.bstop [3] && utility.bstop [4]) {
System.out.println ("Serialize ...");
Utility.serializeout ();
// Call the serialization function to save the breakpoint position in the file
Javaants.setstopfalse ();
Javaants.setstarttrue ();
STOP = True;
} The record of the breakpoint data is a static array to record the breakpoint position. Since there are multiple breakpoint locations, a function can be used for unified preservation:
Public static void serializeout () {
Try {
File TempFile = New File (getTempFileName () "." "TMP");
FileOutputStream file = new fileoutputstream (tempfile); ObjectOutputStream Serialize = New ObjectOutputStream (file);
For (int i = 0; i <5; i ) {
Serialize.writeObject (String.Valueof (nstart [i]));
Serialize.writeObject (String.Valueof (nstop [i]);
}
Serialize.flush ();
File.Close ();
Serialize.close ();
} catch (exception e) {
System.out.println (E.TOString ());
}
}
graphic interface
The graphical interface of the file download system is similar to popular download software - network ants. The implementation of the graphical interface uses the Swing package. It is limited to the space, and details will not be described here. JANTS's graphical interface is shown in Figures 1 and 2.
Figure 1 JANTS main interface
Figure 1 Interface during JANTS download
release
Use the jar command to package all file download systems to javaants.jar files, and join the MeniFest.mf file, specify main-class.
Packing code: jar cfv *. * Javants.jar
Run code: javaw -classpath javants.jar main