本文共 1420 字,大约阅读时间需要 4 分钟。
- 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());
- URLConnection conn = url.openConnection();
-
- int fileSize = conn.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
- {
- button.setEnabled(true);
- 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);
本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1186762,如需转载请自行联系原作者