Multi-thread download in java

Source: Internet
Author: User

Package donghongyujava. gui; import java. awt. event. actionEvent; import java. awt. event. actionListener; import java. io. file; import java. io. inputStream; import java. io. randomAccessFile; import java.net. httpURLConnection; import java.net. URL; import javax. swing. JButton; import javax. swing. JFrame; import javax. swing. JLabel; import javax. swing. JTextField; import javax. swing. plaf. insetsUIResource; public class downlevels EJframe_v2 extends JFrame {private JLabel downlodeJlabel; private JTextField downlodeJTextField; private JButton downlodeJButton; public DownlodeJframe_v2 () {super ("Download page"); this. setLayout (null); downlodeJlabel = new JLabel ("Download connection:"); downlodeJlabel. setBounds (20, 30, 80, 30); downlodeJTextField = new JTextField ("http: // 172.22.65.22: 8080/day31/vedio/test. rmvb "); downlodeJTextField. setBounds (90, 30,350, 30 ); DownlodeJButton = new JButton ("Download Now"); downlodeJButton. setMargin (new InsetsUIResource (0, 0, 0, 0); downlodeJButton. setBounds (200,120,100, 40); add (downlodeJlabel); add (downlodeJTextField); add (downlodeJButton); downlodeJButton. addActionListener (new MyActionListener (); this. setSize (500,300); this. setLocationRelativeTo (null); this. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE); this. setVisible (true);} pub Lic static void main (String [] args) {new DownlodeJframe_v2 ();} // internal class of event listening MyActionListener implements ActionListener {// declare Random access File private RandomAccessFile access for random access; @ Overridepublic void actionreceivmed (ActionEvent e) {// TODO Auto-generated method stub // The downlodeJButton cannot be set. setEnabled (false); // get the download link final String path = downlodeJTextField. getText (); try {// create the url object URL = new url (Path); // HttpURLConnection supports URLConnection with specific HTTP functions. /** Each HttpURLConnection instance can be used to generate a single request, but other instances can transparently share the basic network connected to the HTTP * server. After a request, call the close () method on InputStream or OutputStream * of HttpURLConnection to release the network resources associated with the instance, but it has no effect on the shared persistent connections. If the persistent connection is idle when * disconnect () is called, the basic socket may be disabled. * /// The openConnection (Proxy proxy) in the call url is similar to openConnection (). // The difference is that the connection is established through the specified Proxy; protocol handlers that do not support proxy will ignore this proxy parameter and establish a normal connection. HttpURLConnection httpURLConnection = (HttpURLConnection) url. openConnection (); // get the size of the target resource int size = httpURLConnection. getContentLength (); // get the name of the target resource and set the corresponding save name // substring (int beginIndex) to return a new string, it is a substring of this string // It starts from the character at the specified index until the end of this string. // LastIndexOf (String str) returns the index at the rightmost of the substring. File file = new File ("E:" + path. substring (path. lastIndexOf ("/"); // create a RandomAccessFile instance based on the file name. This type of instance supports reading and writing random access files. // RandomAccessFile (File file, String mode) creates a random access File stream that reads from and writes to/(Optional). The File is specified by the file parameter. // Mode Value:/** Value Meaning ** "r" is enabled in read-only mode. Any write method that calls the result object will throw an IOException. "Rw" * open for reading and writing. If the file does not exist, try to create it. "Rws" is enabled for reading and writing. For * "rw", it is also required that each update of the file content or metadata be synchronized to the underlying storage device. "Rwd" is enabled for reading and writing. For * "rw", it is also required that each update of the file content be synchronized to the underlying storage device. */Access = new RandomAccessFile (file, "rw"); // set the file size access. setLength (size); // close the random access to the file stream and release all system resources associated with the stream. Access. close (); // indicates that the server may not have other requests in the near future. HttpURLConnection. disconnect (); // define the number of threads int threadNumber = 3; // write data to the file created with the same size and type as the target file for (int I = 1; I <= threadNumber; I ++) {// calculate the download size that each thread needs to share based on the total size of the target resource. int blockSize = size/threadNumber; // calculate the start download position of each thread. final int startSize = (I-1) * blockSize; int temp = I * blockSize-1; // determine whether the currently running thread is the last if (I = threadNumber) {if (temp <size) {temp = size ;}} // final int endSize = temp ;// Final RandomAccessFile threadFile = new RandomAccessFile (file, "rw"); // create Thread new Thread () {public void run () {// create a resource file in a connection try {// create a url object URL = new url (path) based on the path of the target resource ); // open the link HttpURLConnection httpURLConnection = (HttpURLConnection) url. openConnection (); // set general request attributes. HttpURLConnection. setRequestProperty ("Range", "bytes =" + startSize + "-" + endSize); // get the input stream object InputStream after connection is = httpURLConnection. getInputStream (); // sets the threadFile where the file starts to be written. seek (startSize); // create byte buffer in the buffer [] = new byte [1024]; // read the file length int len = 0; while (len = is. read (buffer ))! =-1) {threadFile. write (buffer, 0, len);} // release resource is. close (); threadFile. close (); httpURLConnection. disconnect ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}. start () ;}} catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace ();}}}}

 

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.