下载器-http 进度条 文件读写

 

 

 

  
  
  
  
  1. final JButton button = new JButton("下载");  
  2. button.addActionListener(new ActionListener() 
  3.     public void actionPerformed(ActionEvent e) 
  4.     { 
  5.         new Thread() 
  6.         { 
  7.             @Override 
  8.             public void run() 
  9.             { 
  10.                 button.setEnabled(false);//设置按钮在下载过程中不可操作 
  11.                 FileOutputStream fos = null
  12.                 try 
  13.                 { 
  14.                     URL url = new URL(txtFilefjavaindexhtml.getText());//建立HTTP连接 
  15.                     URLConnection conn = url.openConnection();//创建连接对象 
  16.                      
  17.                     int fileSize = conn.getContentLength();//用getContentLength()得到连接对象的文件大小 
  18.                      
  19.                     InputStream is = conn.getInputStream(); 
  20.                     byte[] buffer = new byte[1024]; 
  21.                     int length = 0
  22.                      
  23.                     fos = new FileOutputStream(txtFilefjavaindexhtml_1.getText()); 
  24.                              
  25.                     double downSize = 0
  26.                     while (-1 != (length = is.read(buffer))) 
  27.                     { 
  28.                         downSize += length; 
  29.                         double percent = downSize * 100 / fileSize;//计算下载百分比 
  30.                         fos.write(buffer, 0, length); 
  31.                         progressBar.setValue((int) percent);//设置进度条变化 
  32.                     } 
  33.                 } 
  34.                 catch (MalformedURLException e1) 
  35.                 { 
  36.                     e1.printStackTrace(); 
  37.                 } 
  38.                 catch (IOException e1) 
  39.                 { 
  40.                     e1.printStackTrace(); 
  41.                 } 
  42.                 finally//输出流要记得在fanally关掉 
  43.                 { 
  44.                     button.setEnabled(true);//在finally中恢复按钮可操作 
  45.                     if (null != fos) 
  46.                     { 
  47.                         try 
  48.                         { 
  49.                             fos.close(); 
  50.                         } 
  51.                         catch (IOException e1) 
  52.                         { 
  53.                             e1.printStackTrace(); 
  54.                         } 
  55.                     } 
  56.                 } 
  57.             } 
  58.         }.start(); 
  59.          
  60.     } 
  61. }); 
  62. button.setFont(new Font("宋体", Font.PLAIN, 24)); 
  63. button.setBounds(101649737); 
  64. frame.getContentPane().add(button); 
  65.  
  66. progressBar = new JProgressBar(); 
  67. progressBar.setBounds(15216427237); 
  68. frame.getContentPane().add(progressBar);//进度条按钮 

 

本文出自 “天空没有痕迹但我飞过” 博客,转载请与作者联系!

你可能感兴趣的:(url)