2011-01-15 17 views
13

Come posso utilizzare la libreria per scaricare un file e stampare i byte salvati? Ho provato a utilizzareScarica il file usando java apache commons?

import static org.apache.commons.io.FileUtils.copyURLToFile; 
public static void Download() { 

     URL dl = null; 
     File fl = null; 
     try { 
      fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip"); 
      dl = new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip"); 
      copyURLToFile(dl, fl); 
     } catch (Exception e) { 
      System.out.println(e); 
     } 
    } 

ma non riesco a visualizzare i byte o una barra di avanzamento. Quale metodo dovrei usare?

public class download { 
    public static void Download() { 
     URL dl = null; 
     File fl = null; 
     String x = null; 
     try { 
      fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip"); 
      dl = new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip"); 
      OutputStream os = new FileOutputStream(fl); 
      InputStream is = dl.openStream(); 
      CountingOutputStream count = new CountingOutputStream(os); 
      dl.openConnection().getHeaderField("Content-Length"); 
      IOUtils.copy(is, os);//begin transfer 

      os.close();//close streams 
      is.close();//^ 
     } catch (Exception e) { 
      System.out.println(e); 
     } 
    } 

risposta

13

Se si sta cercando un modo per ottenere il numero totale di byte prima del download, è possibile ottenere questo valore dall'intestazione Content-Length nella risposta http.

Se si desidera solo il numero finale di byte dopo il download, è più semplice controllare la dimensione del file su cui si scrive.

Tuttavia, se si desidera visualizzare l'attuale stato di avanzamento dei quanti byte sono stati scaricati, si potrebbe voler estendere apache CountingOutputStream per avvolgere il FileOutputStream in modo che ogni volta che i metodi write vengono chiamati Conta il numero di byte di passaggio e aggiornamento la barra di avanzamento.

Aggiornamento

Ecco una semplice implementazione di DownloadCountingOutputStream. Non sono sicuro che tu abbia familiarità con l'uso di ActionListener oppure no, ma è una classe utile per l'implementazione della GUI.

public class DownloadCountingOutputStream extends CountingOutputStream { 

    private ActionListener listener = null; 

    public DownloadCountingOutputStream(OutputStream out) { 
     super(out); 
    } 

    public void setListener(ActionListener listener) { 
     this.listener = listener; 
    } 

    @Override 
    protected void afterWrite(int n) throws IOException { 
     super.afterWrite(n); 
     if (listener != null) { 
      listener.actionPerformed(new ActionEvent(this, 0, null)); 
     } 
    } 

} 

Questo è l'esempio di utilizzo:

public class Downloader { 

    private static class ProgressListener implements ActionListener { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      // e.getSource() gives you the object of DownloadCountingOutputStream 
      // because you set it in the overriden method, afterWrite(). 
      System.out.println("Downloaded bytes : " + ((DownloadCountingOutputStream) e.getSource()).getByteCount()); 
     } 
    } 

    public static void main(String[] args) { 
     URL dl = null; 
     File fl = null; 
     String x = null; 
     OutputStream os = null; 
     InputStream is = null; 
     ProgressListener progressListener = new ProgressListener(); 
     try { 
      fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip"); 
      dl = new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip"); 
      os = new FileOutputStream(fl); 
      is = dl.openStream(); 

      DownloadCountingOutputStream dcount = new DownloadCountingOutputStream(os); 
      dcount.setListener(progressListener); 

      // this line give you the total length of source stream as a String. 
      // you may want to convert to integer and store this value to 
      // calculate percentage of the progression. 
      dl.openConnection().getHeaderField("Content-Length"); 

      // begin transfer by writing to dcount, not os. 
      IOUtils.copy(is, dcount); 

     } catch (Exception e) { 
      System.out.println(e); 
     } finally { 
      IOUtils.closeQuietly(os); 
      IOUtils.closeQuietly(is); 
     } 
    } 
} 
+0

Come estenderei Apache per usarlo? fl = new File (System.getProperty ("user.home"). replace ("\\", "/") + "/Desktop/Screenshots.zip"); dl = new URL ("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip"); OutputStream os = new FileOutputStream (fl); InputStream is = dl.openStream(); ConteggioOutputStream count = new CountingOutputStream (os); dl.openConnection().getHeaderField ("Content-Length"); IOUtils.copy (is, os); // inizio trasferimento Sto facendo bene? – Kyle

+0

Ti dispiacerebbe aggiungere il codice sopra alla tua domanda? È difficile da leggere. Proverò ad aiutare. – gigadot

+0

Ho aggiunto il codice grazie per l'aiuto. – Kyle

10

commons-io ha IOUtils.copy(inputStream, outputStream). Quindi:

OutputStream os = new FileOutputStream(fl); 
InputStream is = dl.openStream(); 

IOUtils.copy(is, os); 

E IOUtils.toByteArray(is) può essere utilizzato per ottenere i byte.

Ottenere il numero totale di byte è una storia diversa. Gli stream non ti danno alcun totale - possono solo darti quello che è attualmente disponibile nel flusso. Ma dal momento che è un flusso, può avere più in arrivo.

Ecco perché http ha il suo modo speciale di specificare il numero totale di byte. È nell'intestazione della risposta Content-Length. Quindi dovresti chiamare url.openConnection() e quindi chiamare getHeaderField("Content-Length") sull'oggetto URLConnection. Restituirà il numero di byte come stringa. Quindi usa Integer.parseInt(bytesString) e otterrai il totale.

+0

Hmm .. c'è un modo per visualizzare i byte scaricati da questo flusso? Sto guardando ma non vedo un modo. Grazie per la risposta. – Kyle

+0

'IOUtils.toByteArray (..)' – Bozho

+0

btw, i byte stessi o il loro conteggio? – Bozho

Problemi correlati