09_多线程下载_获取文件长度&计算下载范围


package com.itheima.multiThreadDownload;
//import java.net.MalformedURLException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
//import java.net.URLConnection;

public class MultiThreadDownload {
     private static String path = "http://127.0.0.1:8080/FeiQ.exe";
     private static int threadCount= 3;//不搞那么多就搞三个线程.
     public static void main(String[] args) {
        //①联网获取要下载的文件长度
        try {
            URL url = new URL(path);
            //URLConnection openConnection = url.openConnection();
            HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
            openConnection.setRequestMethod("GET");
            openConnection.setConnectTimeout(10000);
            int responseCode = openConnection.getResponseCode();
            if(responseCode==200){
                //获取要下载的文件长度
                //int contentLength = openConnection.getContentLength();
                //long contentLengthLong = openConnection.getContentLengthLong();
                int contentLength = openConnection.getContentLength();
                //在本地创建一个一样的文件
                RandomAccessFile file = new RandomAccessFile(getFilename(path), "rw");//第一个叫file或者说是name(路径),第二个参数叫mode
                //名字可以通过路径去获取,截取这个路径最后一个斜杠.剩下的这个就是我要下载的文件名
                //file.setLength(contentLengthLong);//文件创建出来之后去设置文件的长度
                file.setLength(contentLength);//文件创建出来之后去设置文件的长度
                //计算每一个线程要下载多少数据
                //int blockSize = contentLengthLong/threadCount;
                int blockSize = contentLength/threadCount;
                //计算每一个线程要下载的数据范围
                for (int i = 0; i < threadCount; i++) {
                    //用i和blockSize来确定startIndex和endIndex
                    int startIndex  = i*blockSize; 
                    int endIndex = (i+1)*blockSize-1;
                    if(i==threadCount-1){
                        //说明是最后一个线程
                        endIndex = contentLength-1;
                    }
                }
            }
        } //catch (MalformedURLException e) {
      catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    private static String getFilename(String path) {
        String[] split = path.split("/");//拿斜杠去切
        
        return split[split.length-1];
    }
}

接下来得创建多个线程,在多线程里面去创建不同的数据。

原文地址:https://www.cnblogs.com/ZHONGZHENHUA/p/7076494.html