Java 网络编程之Http(二):Swing下载进度条JProgressBar使用

前言

做一个带有下载进度提示的小程序,通过HttpURLConnection下载文件,并实时显示下载进度。

环境

jdk1.8
eclipse
Windows 10

结构

在这里插入图片描述

代码

1.启动测试部分(DownloadTest)

下载链接:随便百度的360下载
保存路径:电脑桌面

package lyrics.download;

import lyrics.download.Service.DownloadService;

/**
 * DownloadTest
 * 
 * @author lyrics
 * @since 2020/06/13
 */
public class DownloadTest {

	/**
	 * main
	 * 
	 * @param args arguments
	 * @author lyrics
	 * @since 2020/06/13
	 */
	public static void main(String[] args) {
		DownloadService downloadService = new DownloadService(); 
		String url = "https://down.360safe.com/inst.exe";
		String path = "C:\\Users\\lyrics\\Desktop";
		if(!downloadService.download(url, path)) {
			System.out.println("Download failed!");
		}
		System.out.println("Download successful!");
	}
}

2.界面部分(DownloadUI)

package lyrics.download.ui;

import javax.swing.JDialog;
import javax.swing.JProgressBar;
import javax.swing.JLabel;

/**
 * DownloadUI
 * 
 * @author lyrics
 * @since 2020/06/13
 */
public class DownloadUI extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public JProgressBar progressBar = new JProgressBar();
	public JLabel lblDownloadProgress = new JLabel("progress");

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			DownloadUI dialog = new DownloadUI();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public DownloadUI() {
		setTitle("Dowmload");
		setBounds(100, 100, 447, 137);
		getContentPane().setLayout(null);
			
		progressBar.setBounds(37, 32, 259, 21);
		progressBar.setMaximum(100);
		getContentPane().add(progressBar);
			
		lblDownloadProgress.setBounds(324, 32, 72, 18);
		getContentPane().add(lblDownloadProgress);
	}
}

3.下载服务部分(DownloadService)

package lyrics.download.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.swing.JDialog;
import javax.swing.JOptionPane;

import lyrics.download.ui.DownloadUI;

/**
 * DownloadService
 * 
 * @author lyrics
 * @since 2020/06/13
 */
public class DownloadService {

	private DownloadUI downloadUI = new DownloadUI();
	private int downloadLength = 0;
	
	private void openDownloadUI() {
		try {
			downloadUI.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			downloadUI.setVisible(true);
			downloadUI.setLocationRelativeTo(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * download
	 * 
	 * @param uri download URL
	 * @param path save path
	 * @author lyrics
	 * @since 2020/06/13
	 */
	public boolean download(String uri, String path) {
		openDownloadUI();
		Callback callback = new Callback() {

			@Override
			public void progress(int progress) {
				downloadUI.progressBar.setValue(progress);
				downloadUI.lblDownloadProgress.setText(progress + "%");
			}

			@Override
			public void finish() {
				JOptionPane.showMessageDialog(null, "Download successed!","Message",JOptionPane.INFORMATION_MESSAGE);
				downloadUI.dispose();
			}
			
		};
		boolean download = false;
		try {
			download = download(uri, path, callback);
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
		return download;
	}
	
	private boolean download(String uri, String path,Callback callback) throws IOException {
		URL url = new URL(uri);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setUseCaches(false);
		conn.setConnectTimeout(5000);
		conn.connect();
			
		Map<String, List<String>> map = conn.getHeaderFields();
		downloadLength = Integer.parseInt(map.get("Content-Length").get(0));
		   
		String fileName = uri.substring(uri.lastIndexOf("/") + 1);
		File file = new File(path + "\\" + fileName);
		if(!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream fileOutputStream = new FileOutputStream(file); 
		InputStream input = conn.getInputStream();
		
		int len = 0;
		int count = 0;
		byte[] data = new byte[1024];
		while((len = input.read(data))!=-1) {
			fileOutputStream.write(data, 0, len);
			count += len;
			callback.progress(count*100/downloadLength);
		}
		fileOutputStream.close();
		input.close();
		callback.finish();
		return true;
	} 
	
	private static interface Callback {
		void progress(int progress);
		void finish();
	}
}

演示

下载开始:
下载开始
下载中:
下载中
下载结束:
下载结束

结束

写在最后,本程序基本功能肯定没啥问题,但是可能有些小瑕疵,比如下载文件的大小用的int,文件大一点说不定就溢出了呢。等等吧,瑕疵之处,多多包涵。晚安!!!!!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值