Java multithreaded download file instance details

  • 2020-06-19 10:11:48
  • OfStack

Example of this article for you to share Java multithreaded download file specific code, for your reference, the specific content is as follows


import java.io.File; 
import java.io.InputStream; 
import java.io.RandomAccessFile; 
import java.net.HttpURLConnection; 
import java.net.URL; 
 
public class MulThreadDownload { 
  public static void main(String[] args) throws Exception { 
    String path = "http://192.168.1.100:8080/Hello/Big.exe"; 
    new MulThreadDownload().download(path, 3); 
  } 
 
  /** 
   *  The download file  
   * 
   * @param path 
   *       Network file path  
   * @param threadSize 
   *       The number of threads  
   * @throws Exception 
   */ 
  private void download(String path, int threadSize) throws Exception { 
    URL url = new URL(path); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    connection.setRequestMethod("GET"); 
    connection.setConnectTimeout(5000); 
    if (connection.getResponseCode() == 200) { 
      int length = connection.getContentLength();//  Gets the network file length  
      File file = new File(getFileName(path)); 
      //  Generate locally 1 Three files of the same length as the network file  
      RandomAccessFile accessFile = new RandomAccessFile(file, "rwd"); 
      accessFile.setLength(length); 
      accessFile.close(); 
 
      //  Calculate the amount of data each thread is responsible for downloading  
      int block = length % threadSize == 0 ? length / threadSize : length 
          / threadSize + 1; 
      for (int threadId = 0; threadId < threadSize; threadId++) { 
        new DownloadThread(threadId, block, url, file).start(); 
      } 
    } else { 
      System.out.println("download fail"); 
    } 
  } 
 
  private class DownloadThread extends Thread { 
 
    private int threadId; 
    private int block; 
    private URL url; 
    private File file; 
 
    public DownloadThread(int threadId, int block, URL url, File file) { 
      this.threadId = threadId; 
      this.block = block; 
      this.url = url; 
      this.file = file; 
    } 
 
    @Override 
    public void run() { 
      int start = threadId * block; //  Where does the compute thread start downloading from the network file  
      int end = (threadId + 1) * block - 1; //  Calculate where the download to the network file ends  
      try { 
        RandomAccessFile accessFile = new RandomAccessFile(file, "rwd"); 
        accessFile.seek(start); // from start start  
 
        HttpURLConnection connection = (HttpURLConnection) url 
            .openConnection(); 
        connection.setRequestMethod("GET"); 
        connection.setConnectTimeout(5000); 
        // Set the scope to get resource data from start to end 
        connection.setRequestProperty("Range", "bytes=" + start + "-" 
            + end); 
        // Note that the multithreaded download status code is  206  not 200 
        if (connection.getResponseCode() == 206) { 
          InputStream inputStream = connection.getInputStream(); 
          byte[] buffer = new byte[1024]; 
          int len = 0; 
          while ((len = inputStream.read(buffer)) != -1) { 
            accessFile.write(buffer, 0, len); 
          } 
          accessFile.close(); 
          inputStream.close(); 
        } 
        System.out.println(" The first " + (threadId + 1) + " A thread has been downloaded "); 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
    } 
  } 
 
  /** 
   *  Get file name  
   * 
   * @param path 
   *       Network file path  
   * @return 
   */ 
  private String getFileName(String path) { 
    return path.substring(path.lastIndexOf("/") + 1); 
  } 
} 

Related articles: