Underc0de

Programación General => Java => Mensaje iniciado por: ProcessKill en Febrero 24, 2010, 04:16:01 PM

Título: Descargar archivos de la web usando un progressBar
Publicado por: ProcessKill en Febrero 24, 2010, 04:16:01 PM
[ -Consola ]
____________________________________________________________________________________________

Wait..
http://www.tecnun.es/asignaturas/Informat1/ayudainf/aprendainf/Java/Java2.pdf
______________________________________________________

Date: Sat Sep 05 10:56:19 VET 2009
Last Modified: Tue Feb 08 11:12:02 VET 2005
Expiration: Wed Dec 31 20:00:00 VET 1969
Host: www.tecnun.es Port: 80
Path: /asignaturas/Informat1/ayudainf/aprendainf/Java/Java2.pdf
Name: Java2.pdf
Size: 2050138
Protocol: http://
______________________________________________________
Init.
Receiving data..


____________________________________________________________________________________________

[ -CODE -]

Código (java) [Seleccionar]

import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;

/**
* Hilo para descarga de un archivo desde una URL
* implementando un progressbar
*
* @author L-EYER
*
* @see GlassFish Tools Bundle For Eclipse
   Version: 0.9.9
*/
public class Downloader extends Thread{
   private URL           url          =   null;
   private JProgressBar  progressBar  =   null;
   private URLConnection connection   =   null;
   /**
   * Constructor
   *
   * @param URL
   * @param Barra de Progreso
   */
   public Downloader(
         final URL URL,
         JProgressBar progress) {
   super("Downloader");
   this.url = URL; this.progressBar = progress;
   progressBar.setStringPainted(true);}
   @Override
   public void run() {
      try {
       System.out.println("Wait..");
       connection = url.openConnection();
       connection.connect();
          progressBar.setMinimum(0);
          progressBar.setForeground(new Color(160,20,9,100));
          progressBar.setBorderPainted(true);
         } catch (IOException e) {System.err.println("Error in conection!");System.exit(0);
         } catch (Exception e) {
            System.err.println(e);System.exit(0);
         }
      int read = 0;
      final int SIZE = getLength(url);
      progressBar.setMaximum(SIZE);
      InputStream stream  =  null;
      try {
         stream = connection.getInputStream();
         System.out.println(url.toExternalForm());
         System.out.println("______________________________________________________\n");
         System.out.println("Date: "+new Date(connection.getDate()));
         System.out.println("Last Modified: "+ new Date(connection.getLastModified()));
         System.out.println("Expiration: " + new Date(connection.getExpiration()));
         System.out.println("Host: "+url.getHost()+" Port: "+url.getDefaultPort());
         System.out.println("Path: "+url.getPath());
         System.out.println("Name: "+getFileName(url));
         System.out.println("Size: "+getLength(url));
         System.out.println("Protocol:"+url.getProtocol()+"://");
         System.out.println("______________________________________________________");
         final FileOutputStream fileOutputStream = new FileOutputStream(getFileName(url));
         final byte[] data =
            new byte[ SIZE ];
          try {
               Thread.sleep(100);
            } catch (InterruptedException e) {System.err.println(e);System.exit(0);
            }
         int offset = 0;
         System.out.println("Init.");
         System.out.println("Receiving data..");
         while((read = stream.read(data)) > 0){
             offset += read;
            progressBar.setValue(offset);
            fileOutputStream.write(data,
                  0,
                  read);
         }
         System.out.println("Completed! 100%");
         JOptionPane.showMessageDialog(new JFrame(),
               "Completed!",
               "100%",
               JOptionPane.INFORMATION_MESSAGE);
         progressBar.setValue(0);
         try{
         stream.close();
         fileOutputStream.flush();
         fileOutputStream.close();
             offset = 0;
            }catch (Exception e) {System.err.println(e);System.exit(0);
            }
      }catch (IOException e) {
      System.err.println(e+"ERROR:URL");System.exit(0);
        }catch (Exception e) {
      System.err.println(e);
       }
       super.run();
      }
       final int getLength(URL urlFile){
      URLConnection connection = null;
      int size = 0;
      try {
      connection = urlFile.openConnection();
         size = connection.getContentLength();
      } catch (IOException e) {
         System.err.println(e+":ERROR");System.exit(0);
      } catch (Exception e) {
         System.err.println(e+":ERROR");System.exit(0);
      }
      return size;
   }
   String getFileName(URL URL){
     String path=URL.getPath();
     int lastIndexOf=path.lastIndexOf("/");
     String name = path.substring(lastIndexOf+1);
       return name;
   }
} class mainClass {
   public static void main(final String[] args){
      try{
         final JProgressBar progressBar = new JProgressBar();
         URL url = new URL("http://www.tecnun.es/asignaturas/Informat1/ayudainf/aprendainf/Java/Java2.pdf");
         Downloader downloader = new Downloader(url,progressBar);
         downloader.start();
      } catch (MalformedURLException e) {
      System.err.println("Error: Protocol"+e);
      System.exit(0);
      } catch (Exception e) {
         System.err.println(e);
      }
   }