JProgressBar com tranferencia de arquivo

4 respostas
0

bem ao apertar o botao de download eu chamo o metodo download que faz download de um arquivo

URL site = new URL("http://www.appsapps.info/downloads/PesterMe.zip");
 HttpURLConnection connection = (HttpURLConnection) site.openConnection();

     FileOutputStream out = new FileOutputStream("C://PesterMe.zip");

     BufferedInputStream input = new BufferedInputStream(connection.getInputStream());

     maximo = connection.getContentLength();

          //Debugs
     System.out.println("O arquivo possui tamanho de " + maximo + " bytes.");

 byte[] buf = new byte[409600];

 while ( (lenght = input.read(buf)) > 0 )
 out.write(buf, 0, lenght);
 input.close();
 out.close();

esse download ele executa beleza e informa o tamanho do arquivo....

dou um public nas variaveis

public int maximo; //o que eu peguei do conne....
     public int lenght; //
     final int DELAY = maximo;
     Timer t = new Timer(DELAY, this);

e o jprogress ta assim

public void actionPerformed(ActionEvent e) {
      lenght = jProgressBar1.getValue();
      if (lenght == jProgressBar1.getMaximum()) {
          System.out.println("fucku");
         t.stop ();
      }
      jProgressBar1.setValue(lenght);
     }

to ficando doido com isso ja :(

o que ta errado pois chama tudo mais a barra fica parada e so carrega quando termina o download

4 Respostas

Lucas_Bellin

Opa… fiz um código rápido aqui para demonstrar um exemplo de download utilizando JProgressBar… ele também controla a taxa de transferência do download.

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Time;
import java.text.DateFormat;
import java.text.NumberFormat;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;

/**
 *
 * @author Lucas Bellin
 */
public class Download extends JFrame
{
    // classe que extende um Thread para executar o download
    // é necessário para que a Progress seja atualizado enquanto o download estiver sendo feito
    public class Runner extends Thread
    {
        public void run()
        {
            try
            {
                startDownload();
            }
            
            catch ( Exception e )
            {
                System.out.println( "ERRO: " + e.toString() );
            }
        }
    }

    // método main que abre a janela com a Progress e um botão para iniciar ela
    public static void main( String args[] )
    {
        new Download().setVisible( true );
    }

    // link do arquivo de download
    public static final String link = "http://www.seulink.com/download/arquivo.zip";

    /**
     * Download
     *
     */
    public Download()
    {
        initComponents();
    }

    /**
     * startDownload
     *
     */
    private void startDownload()
    {
        try
        {
            progress.setValue( 0 );

            // arquivo local onde o arquivo do download será salvo
            File tmp = new File( "/home/lb/Desktop/setup.zip" );

            downloadFile( link, tmp );

            System.out.println("DONE!");
        }

        catch ( Exception e )
        {
            e.printStackTrace();
        }
    }

    /**
     * downloadFile
     *
     * @param source String
     * @param target File
     * @throws Exception
     */
    private void downloadFile( String source, File target ) throws Exception
    {
        jlMessage.setText( "Conectando ..." );

        URLConnection conn = new URL( source ).openConnection();

        int contentLength = conn.getContentLength();

        progress.setMinimum( 0 );
        progress.setMaximum( contentLength );
        progress.setValue( 0 );

        int bytesRead = 0;

        BufferedInputStream in = new BufferedInputStream( conn.getInputStream() );
        BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream( target ) );

        byte[] buffer = new byte[4096]; // 4kB

        jlMessage.setText( "Baixando ..." );

        DateFormat tf = DateFormat.getTimeInstance();

        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits( 1 );
        nf.setMaximumFractionDigits( 1 );
        nf.setGroupingUsed( true );

        long timeStarted = System.currentTimeMillis();

        while ( true )
        {
            int n = in.read( buffer );

            if ( n == -1 )
            {
                break;
            }

            out.write( buffer, 0, n );

            bytesRead += n;

            progress.setValue( bytesRead );

            long timeElapsed = System.currentTimeMillis() - timeStarted;

            double downloadRate = ( bytesRead / 1000.0 ) / ( timeElapsed / 1000.0 );

            long timeRemaining =  (long) ( 1000 * ( ( contentLength - bytesRead ) / ( downloadRate * 1000 ) ) );

            long timeArrival = timeStarted + timeElapsed + timeRemaining;

            jlMessage.setText( "Inciado: " + tf.format( new Time( timeStarted ) ) +
                    ", Chegada: " + tf.format( new Time( timeArrival ) ) +
                    ", Transferência: " + nf.format( downloadRate ) + " kB/s" );
        }

        in.close();
        out.close();

        System.out.println( target.exists() );

        jlMessage.setText( "Download concluído!" );
    }

    private void initComponents()
    {
        setLayout( new GridBagLayout() );
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        setSize( 400, 150 );
        setLocationRelativeTo( null );

        buttonsPane.setLayout( new FlowLayout() );
        buttonsPane.add( btStart );

        jlMessage.setFont( new Font( "SansSerif" , Font.PLAIN, 10 ) );

        add( jlMessage, new GridBagConstraints( 0, 0, 1, 1, 1.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
                new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        add( progress, new GridBagConstraints( 0, 1, 1, 1, 1.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
                new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        add( buttonsPane, new GridBagConstraints( 0, 2, 1, 1, 1.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
                new Insets( 5, 5, 5, 5 ), 0, 0 ) );

        btStart.addActionListener( new AbstractAction()
        {
            public void actionPerformed( ActionEvent e )
            {
                new Runner().start();
            }
        });
    }

    private JLabel jlMessage = new JLabel( "Message:" );
    private JProgressBar progress = new JProgressBar();
    private JPanel buttonsPane = new JPanel();
    private JButton btStart = new JButton( "Start download" );
}

qualquer dúvida poste aí!! :smiley:

R

gruder: O ponto mais importante para que você possa atualizar sua GUI no decorrer de um processo demorado é o seguinte: esse processo demorado tem que rodar numa thread diferente daquela em que você atualiza a GUI. E, para que o processo possa notificar a GUI, é preciso usar o método EventQueue.invokeLater() :

http://java.sun.com/javase/6/docs/api/java/awt/EventQueue.html#invokeLater(java.lang.Runnable)

A partir da versão 6 o Java oferece a classe SwingWorker, criada especialmente para ajudar a resolver problemas como esse:

http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html

Lucas: seu código está legal mas é perigoso atualizar a GUI numa thread que não seja a do Swing. Falo de trechos como os que seguem abaixo:

progress.setValue( 0 );
jlMessage.setText( "Conectando ..." );

Atualizações de GUI como estas têm de ser feitas através de EventQueue.invokeLater() .

Lucas_Bellin

humm… blz… já conhecia essa chamada mas não sabia que poderiam ser gerados problemas utilizando da maneira q fiz… dica anotada!!

0

perfeito seu codigo lucas muito obrigado vou ver o que ta diferente no meu codigo e vou basear no seu valeus mesmo e

roger vou dar uma lida nista daí

Criado 9 de junho de 2009
Ultima resposta 10 de jun. de 2009
Respostas 4
Participantes 3