java实现多线程URL下载

写好下载器的UI界面,点击“下载”,触发以下事件

1、构造一个下载器downloader;

2、获得所有的下载信息List<DownloadInfo> info;

3、添加进度条;

4、开启下载线程;


DownloadUI.java

package cn.yif.URL;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.util.List;


public class DownloadUI extends JFrame implements ActionListener {

    private JLabel labURLFile;    //源文件标签
    private JLabel labLocalDir;   //目标文件标签
    private JLabel labCount;

    private JTextField tfURLFile;
    private JTextField tfLocalFile;
    private JTextField tfCount;
    private JButton btnStart;
    public  JProgressBar[] bars;

    private static final long serialVersionUID = -5035867481307416008L;
    public DownloadUI(){
        init();
       this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    private void init(){
        this.setTitle("主窗口");
        this.setBounds(100, 100, 800, 600);
        this.setLayout(null);

        //srcFile标签
        labURLFile = new JLabel("URL文件:");
        labURLFile.setBounds(10, 10, 80, 50);
        this.add(labURLFile);

        tfURLFile = new JTextField();
        tfURLFile.setBounds(70, 20, 500, 30);
        tfURLFile.setText("http://localhost:8080/hello.txt");
        this.add(tfURLFile);

        labLocalDir = new JLabel("保存路径");
        labLocalDir.setBounds(10, 60, 80, 50);
        this.add(labLocalDir);

        tfLocalFile = new JTextField();
        tfLocalFile.setBounds(70, 75, 500, 30);
        tfLocalFile.setText("D:\\1.txt");
        this.add(tfLocalFile);


        labCount = new JLabel("线程数");
        labCount.setBounds(10, 120, 80, 50);
        this.add(labCount);


        tfCount = new JTextField();
        tfCount.setBounds(70, 130, 500, 30);
        this.add(tfCount);


        btnStart = new JButton("开始");
        btnStart.setBounds(10, 170, 100, 30);
        this.add(btnStart);
        btnStart.addActionListener(this);



        this.setVisible(true);

    }


    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        //开始按钮
        if (source == btnStart){
            String url = tfURLFile.getText();
            String local = tfLocalFile.getText();
            int count = Integer.parseInt(tfCount.getText());

            Downloader downloader = new Downloader(url, local, count, this);
//            2、取得infos
            List<DownloadInfo> infos = downloader.getInfos();
//            3、动态添加进度条
            this.addBars(infos);

//            4、开始下载
            downloader.startDownload();
        }
    }

    private void addBars(List<DownloadInfo> infos) {
        bars = new JProgressBar[infos.size()];
        int yOffset = 210;
        for (DownloadInfo info : infos){
            bars[info.getIndex()] = new JProgressBar();
            bars[info.getIndex()].setMaximum(info.getEnd() - info.getStart() + 1);
            bars[info.getIndex()].setValue(0);
            bars[info.getIndex()].setBounds(10, yOffset + info.getIndex() * 50 , 550, 30);
            this.add(bars[info.getIndex()]);
        }
        this.repaint();
    }

    public  void updateBar(int index, int len) {
        bars[index].setValue(bars[index].getValue() + len);
    }
}
---------------------------------------------------------------------------------------------------

DownloadInfo.java    下载信息

package cn.yif.URL;

public class DownloadInfo {
    private String URL;
    private String local;
    private int start;
    private int end;
    private int index;

    public String getURL() {
        return URL;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public void setEnd(int end) {
        this.end = end;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public void setURL(String URL) {
        this.URL = URL;
    }

    public String getLocal() {
        return local;
    }

    public void setLocal(String local) {
        this.local = local;
    }

    public int getStart() {
        return start;
    }

    public int getEnd() {
        return end;
    }
}
 
 
---------------------------------------------------------------------------------------------------


Downloader.java

package cn.yif.URL;


import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 下载器
 */
public class Downloader {
    private String url;
    private String local;
    private List<DownloadInfo> infos;
    private int count;
    private int fileLength;
    private DownloadUI ui;
    public Downloader(String url, String local, int count, DownloadUI ui) {
        this.url = url;
        this.local = local;
        this.count = count;
        this.ui = ui;
        prepareDownload();
    }

    public List<DownloadInfo> getInfos() {
        return infos;
    }

    /**
     * 准备下载
     */
    private void prepareDownload(){
        try {
//          1、获取URL文件大小
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            fileLength = conn.getContentLength();
//          2、创建本地文件并且设置大小
            RandomAccessFile raf= new RandomAccessFile(local, "rw");
            raf.setLength(fileLength);
            raf.close();
//          3、计算下载信息集合
            initDownloadInfos();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void initDownloadInfos() {
        infos = new ArrayList<DownloadInfo>();
        DownloadInfo info = null;
        int block = fileLength / count;
        for (int i = 0; i < count; i++) {
            info = new DownloadInfo();
            info.setURL(url);
            info.setLocal(local);
            info.setIndex(i);

            info.setStart(i * block);
            if (i != count - 1){
                info.setEnd((i + 1) * block - 1);
            }else{
                info.setEnd(fileLength);
            }
            infos.add(info);
        }

    }

    public void startDownload() {
        for (DownloadInfo info : infos){
            new DownloadThread(info, ui).start();
        }
    }
}
 
 
 
 
---------------------------------------------------------------------------------------------------

DownloadThread.java
 
 

package cn.yif.URL;

import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadThread extends Thread{

    private DownloadInfo info;
    private DownloadUI ui;
    public DownloadThread(DownloadInfo info, DownloadUI ui){
        this.info = info;
        this.ui = ui;
    }

    @Override
    public void run() {
        try {
            URL url = new URL(info.getURL());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Range", "bytes=" + info.getStart() + "-" + info.getEnd());
            InputStream is = conn.getInputStream();

            RandomAccessFile raf = new RandomAccessFile(info.getLocal(), "rw");
            raf.seek(info.getStart());
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = is.read(buffer)) != -1){
                raf.write(buffer, 0 , len);
                ui.updateBar(info.getIndex(), len);
            }
            raf.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 
---------------------------------------------------------------------------------------------------
DownloadApp.java  主程序
public class DownloadApp {
    public static void main(String[] args) {
        new DownloadUI();
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值