java多线程下载网络资源(支持断点续传)

package threadpic;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ThreadDownPic {
static int threadCount = 4;
static int progressThread = 0;

static String path = "http://dlsw.baidu.com/sw-search-sp/soft/3a/12350/QQ_8.1.17255.0_setup.1456298445.exe";
public static void main(String[] args) {

    URL url;
    try {
        url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置一个指定的超时值(以毫秒为单位)
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.setRequestMethod("GET");
        // 返回值从 HTTP 响应消息获取状态码。例如,就以下状态行来说:
        // HTTP/1.0 200 OK
        // HTTP/1.0 401 Unauthorized
        if (conn.getResponseCode() == 200) {
            System.out.println("联网成功!");
            // 获取文件的长度
            int length = conn.getContentLength();
            File file = new File(getFileName());
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            // 设置文件的长度跟网络上获取的长度一致
            raf.setLength(length);
            raf.close();
            int avg = length / threadCount;// 13/3=4...1
            for (int i = 0; i < threadCount; i++) {
                int start = avg * i;
                int end = avg * (i + 1) - 1;
                if (i == threadCount - 1) {
                    end = length - 1;
                }
                System.out.println("线程下载的区间" + start + "---" + end);
                new DownThread(i, start, end).start();
            }
        } else {
            System.out.println("联网失败!");
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static String getFileName(){
    return "D:\\"+path.substring(path.lastIndexOf("/")+1);
}

}

class DownThread extends Thread {

int threadId;
int startIndex;
int endIndex;

public DownThread(int threadId, int startIndex, int endIndex) {
    this.threadId = threadId;
    this.startIndex = startIndex;
    this.endIndex = endIndex;
}

@Override
public void run() {
    try {
        // 创建临时文件进行存储下载的位置
        File file = new File("D:\\"+threadId + ".txt");
        int progressTotal = 0;
        if (!file.exists()) {
            file.createNewFile();
        }else{
            Reader r = new FileReader(file);
            BufferedReader br = new BufferedReader(r);
            //读取临时文件中存储的长度
            progressTotal = Integer.parseInt(br.readLine());
            startIndex+=progressTotal;
            br.close();
        }

        URL url = new URL(ThreadDownPic.path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(8000);
        conn.setReadTimeout(8000);
        // 设置请求数据的区间 Property性质
        conn.setRequestProperty("Range", "bytes=" + startIndex + "-"
                + endIndex);
        // 请求部分数据成功
        if (conn.getResponseCode() == 206) {
            InputStream is = conn.getInputStream();
            byte[] buff = new byte[1024 * 8];
            // 设置读取到的位置
            int index = 0;
            int total = progressTotal;
            RandomAccessFile raf = new RandomAccessFile(
                    ThreadDownPic.getFileName(), "rwd");
            raf.seek(startIndex);
            while ((index = is.read(buff)) != -1) {
                raf.write(buff, 0, index);
                total += index;
                System.out.println(Thread.currentThread().getName() + "下载了"
                        + total + "字节");
                // 向临时文件中写入读取的字节数
                RandomAccessFile rafProgress = new RandomAccessFile(file,
                        "rwd");
                rafProgress.write((total + "").getBytes());
                rafProgress.close();
            }
            System.out
                    .println(Thread.currentThread().getName() + "下载完成!!!");
            ThreadDownPic.progressThread++;
            synchronized (ThreadDownPic.path) {
                if (ThreadDownPic.progressThread == ThreadDownPic.threadCount) {
                    for (int i = 0; i < ThreadDownPic.threadCount; i++) {
                        File progressFile = new File("D:\\"+threadId + ".txt");
                        // 删除临时文件
                        progressFile.delete();
                        ThreadDownPic.progressThread = 0;
                    }
                }
            }
            raf.close();
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值