- final JButton button = new JButton("下载");
- button.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- new Thread()
- {
- @Override
- public void run()
- {
- button.setEnabled(false);//设置按钮在下载过程中不可操作
- FileOutputStream fos = null;
- try
- {
- URL url = new URL(txtFilefjavaindexhtml.getText());//建立HTTP连接
- URLConnection conn = url.openConnection();//创建连接对象
- int fileSize = conn.getContentLength();//用getContentLength()得到连接对象的文件大小
- InputStream is = conn.getInputStream();
- byte[] buffer = new byte[1024];
- int length = 0;
- fos = new FileOutputStream(txtFilefjavaindexhtml_1.getText());
- double downSize = 0;
- while (-1 != (length = is.read(buffer)))
- {
- downSize += length;
- double percent = downSize * 100 / fileSize;//计算下载百分比
- fos.write(buffer, 0, length);
- progressBar.setValue((int) percent);//设置进度条变化
- }
- }
- catch (MalformedURLException e1)
- {
- e1.printStackTrace();
- }
- catch (IOException e1)
- {
- e1.printStackTrace();
- }
- finally//输出流要记得在fanally关掉
- {
- button.setEnabled(true);//在finally中恢复按钮可操作
- if (null != fos)
- {
- try
- {
- fos.close();
- }
- catch (IOException e1)
- {
- e1.printStackTrace();
- }
- }
- }
- }
- }.start();
- }
- });
- button.setFont(new Font("宋体", Font.PLAIN, 24));
- button.setBounds(10, 164, 97, 37);
- frame.getContentPane().add(button);
- progressBar = new JProgressBar();
- progressBar.setBounds(152, 164, 272, 37);
- frame.getContentPane().add(progressBar);//进度条按钮
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。