Pregunta

¿Cómo puedo utilizar la biblioteca para descargar un archivo e imprimir bytes salvo? Intenté usar

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);
        }
    }

pero no puedo mostrar bytes o una barra de progreso. ¿Qué método se debe usar?

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);
        }
    }
¿Fue útil?

Solución

Si usted está buscando una manera de obtener el número total de bytes antes de la descarga, se puede obtener este valor de la cabecera HTTP Content-Length en la respuesta.

Si lo que desea es el número final de bytes después de la descarga, es más fácil de comprobar el tamaño del archivo que acaba de escribir a.

Sin embargo, si desea mostrar los avances actuales de cuántos bytes se han descargado, es posible que desee ampliar Apache CountingOutputStream para envolver el FileOutputStream de manera que cada vez que se llaman los métodos write cuenta el número de bytes que atraviesan y actualizar el progresar bar.

Actualizar

Esta es una implementación sencilla de DownloadCountingOutputStream. No estoy seguro de si está familiarizado con el uso de ActionListener o no, pero es una clase de utilidad para la implementación de interfaz gráfica de usuario.

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));
        }
    }

}

Esta es la muestra de uso:

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);
        }
    }
}

Otros consejos

commons-io tiene IOUtils.copy(inputStream, outputStream) . Por lo tanto:

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

IOUtils.copy(is, os);

Y IOUtils.toByteArray(is) puede ser utilizado para obtener los bytes.

Obtener el número total de bytes es una historia diferente. Arroyos no le dan ninguna totales - que sólo le puede dar lo que está disponible actualmente en el tren. Pero ya que es una corriente, que puede tener más por venir.

Es por eso http tiene su manera especial de especificar el número total de bytes. Es en el Content-Length cabecera de respuesta. Por lo que tendría que llamar url.openConnection() y luego llamar getHeaderField("Content-Length") en el objeto URLConnection. Se devolverá el número de bytes como cadena. A continuación, utilice Integer.parseInt(bytesString) y obtendrá su total.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top