联系客服:400-805-1963

下载器-http 进度条 文件读写
更新:HHH   时间:2023-1-7


 

 

 

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

 

返回开发技术教程...