开启辅助访问 切换到宽版

精易论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

用微信号发送消息登录论坛

新人指南 邀请好友注册 - 我关注人的新帖 教你赚取精币 - 每日签到


求职/招聘- 论坛接单- 开发者大厅

论坛版规 总版规 - 建议/投诉 - 应聘版主 - 精华帖总集 积分说明 - 禁言标准 - 有奖举报

查看: 1206|回复: 23
打印 上一主题 下一主题
收起左侧

[易语言模块源码] JAVA多线程下载源码

[复制链接]
跳转到指定楼层
楼主
发表于 2025-2-3 15:54:33 | 只看该作者 |只看大图 回帖奖励 |正序浏览 |阅读模式   湖南省岳阳市
分享例程
界面截图:
备注说明: -

多线程下载工具JAVA源码   本人写了 许多代码 唯独Java用的比较爽 代码比较烦

nvjava.rar (4.5 KB, 下载次数: 13)


[Java] 纯文本查看 复制代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.RandomAccessFile;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class DownloadTool extends JFrame {
    private JProgressBar progressBar;
    private JButton startButton;
    private ExecutorService executorService;
    private static final int THREAD_COUNT = 4; // 使用4个线程进行下载
    private JLabel speedLabel;
    private JLabel timeLabel;
    private long startTime;
    private AtomicInteger totalDownloadedBytes = new AtomicInteger(0);
    private int fileSize = 0;

    public DownloadTool() {
        setTitle("多线程下载工具");
        setSize(400, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        startButton = new JButton("开始下载");
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                startDownload();
            }
        });

        speedLabel = new JLabel("速度: 0.00 MB/S");
        timeLabel = new JLabel("剩余时间: 00:00:00");

        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); // 使用FlowLayout排列标签
        infoPanel.add(speedLabel);
        infoPanel.add(timeLabel);

        setLayout(new BorderLayout());
        add(infoPanel, BorderLayout.NORTH);
        add(progressBar, BorderLayout.CENTER);
        add(startButton, BorderLayout.SOUTH);
    }

    private void startDownload() {
        String fileURL = "https://dldir1.qq.com/qqfile/qq/QQNT/Windows/QQ_9.9.17_250110_x64_01.exe"; // 替换为实际的文件URL
        String savePath = "qq.exe"; // 替换为实际的保存路径

        try {
            URL url = new URL(fileURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            fileSize = connection.getContentLength();

            executorService = Executors.newFixedThreadPool(THREAD_COUNT);
            int partSize = fileSize / THREAD_COUNT;

            startTime = System.currentTimeMillis();

            for (int i = 0; i < THREAD_COUNT; i++) {
                int startByte = i * partSize;
                int endByte = (i == THREAD_COUNT - 1) ? fileSize : (i + 1) * partSize - 1;
                executorService.execute(new DownloadThread(url, savePath, startByte, endByte));
            }

            new Thread(() -> {
                while (!executorService.isTerminated()) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    updateSpeedAndTime();
                }
                // 确保在所有线程完成后更新进度条到100%
                if (totalDownloadedBytes.get() == fileSize) {
                    SwingUtilities.invokeLater(() -> {
                        progressBar.setValue(100);
                        progressBar.setString("下载完成");
                    });
                }
            }).start();

            executorService.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateSpeedAndTime() {
        long currentTime = System.currentTimeMillis();
        long elapsedTime = currentTime - startTime;
        double speed = (totalDownloadedBytes.get() * 1000.0) / (elapsedTime * 1024 * 1024); // MB/S

        int remainingBytes = fileSize - totalDownloadedBytes.get();
        long remainingTime = (long) (remainingBytes / (speed * 1024 * 1024) * 1000); // 毫秒

        String speedText = String.format("速度: %.2f MB/S", speed);
        String timeText = String.format("剩余时间: %02d:%02d:%02d", 
            remainingTime / 3600000, 
            (remainingTime % 3600000) / 60000, 
            (remainingTime % 60000) / 1000);

        SwingUtilities.invokeLater(() -> {
            speedLabel.setText(speedText);
            timeLabel.setText(timeText);
        });
    }

    private class DownloadThread implements Runnable {
        private URL url;
        private String savePath;
        private int startByte;
        private int endByte;

        public DownloadThread(URL url, String savePath, int startByte, int endByte) {
            this.url = url;
            this.savePath = savePath;
            this.startByte = startByte;
            this.endByte = endByte;
        }

        @Override
        public void run() {
            try {
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Range", "bytes=" + startByte + "-" + endByte);
                InputStream inputStream = connection.getInputStream();
                byte[] buffer = new byte[4096];
                int bytesRead;

                try (RandomAccessFile outputStream = new RandomAccessFile(savePath, "rw")) {
                    outputStream.seek(startByte);
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                        totalDownloadedBytes.addAndGet(bytesRead);
                        updateProgressBar(bytesRead);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private void updateProgressBar(final int bytesRead) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    int progress = (int) ((totalDownloadedBytes.get() * 100.0) / fileSize);
                    progressBar.setValue(progress);

                    double downloadedMB = totalDownloadedBytes.get() / (1024.0 * 1024.0);
                    double totalMB = fileSize / (1024.0 * 1024.0);
                    String progressText = String.format("%.2f MB/%.2f MB", downloadedMB, totalMB);
                    progressBar.setString(progressText);
                }
            });
        }
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new DownloadTool().setVisible(true);
            }
        });
    }
}




友情提醒:请选择可信度高的模块,勿用未知模块,防止小人在模块内加入木马程序。【发现问题模块请到站务投诉】。

签到天数: 10 天

24
发表于 4 天前 | 只看该作者   浙江省台州市
111111111111111111111111111111
回复 支持 反对

使用道具 举报

签到天数: 2 天

23
发表于 2025-4-25 19:26:18 | 只看该作者   湖南省娄底市
支持开源,感谢分享
回复 支持 反对

使用道具 举报

签到天数: 3 天

22
发表于 2025-4-24 21:21:20 | 只看该作者   江苏省泰州市
544654564561231
回复 支持 反对

使用道具 举报

签到天数: 3 天

21
发表于 2025-4-12 20:55:37 | 只看该作者   江苏省南京市
感谢分享
回复 支持 反对

使用道具 举报

签到天数: 12 天

20
发表于 2025-4-8 20:29:51 | 只看该作者   广东省广州市
感谢你对社区做出的贡献!
回复 支持 反对

使用道具 举报

签到天数: 3 天

19
发表于 2025-4-6 20:49:55 | 只看该作者   江苏省南京市
感谢分享
回复 支持 反对

使用道具 举报

结帖率:100% (8/8)

签到天数: 8 天

18
发表于 2025-4-2 01:00:00 | 只看该作者   浙江省温州市
66666666666666666666666666
回复 支持 反对

使用道具 举报

结帖率:100% (1/1)
17
发表于 2025-3-19 14:43:38 | 只看该作者   安徽省安庆市
多线程下载工具JAVA源码   本人写了 许多代码
回复 支持 反对

使用道具 举报

签到天数: 3 天

16
发表于 2025-3-19 14:13:21 | 只看该作者   广西壮族自治区南宁市

顶大神
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 致发广告者

发布主题 收藏帖子 返回列表

sitemap| 易语言源码| 易语言教程| 易语言论坛| 易语言模块| 手机版| 广告投放| 精易论坛
拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论,本站内容均为会员发表,并不代表精易立场!
论坛帖子内容仅用于技术交流学习和研究的目的,严禁用于非法目的,否则造成一切后果自负!如帖子内容侵害到你的权益,请联系我们!
防范网络诈骗,远离网络犯罪 违法和不良信息举报电话0663-3422125,QQ: 793400750,邮箱:[email protected]
网站简介:精易论坛成立于2009年,是一个程序设计学习交流技术论坛,隶属于揭阳市揭东区精易科技有限公司所有。
Powered by Discuz! X3.4 揭阳市揭东区精易科技有限公司 ( 粤ICP备12094385号-1) 粤公网安备 44522102000125 增值电信业务经营许可证 粤B2-20192173

快速回复 返回顶部 返回列表