简体   繁体   English

使用java apache commons下载文件?

[英]Download file using java apache commons?

How can I use the library to download a file and print out bytes saved? 如何使用库下载文件并打印保存的字节? I tried using 我试过用

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

but I cannot display bytes or a progress bar. 但我无法显示字节或进度条。 Which method should I use? 我应该使用哪种方法?

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

If you are looking for a way to get the total number of bytes before downloading, you can obtain this value from the Content-Length header in http response. 如果您正在寻找在下载之前获取总字节数的方法,则可以从http响应中的Content-Length标头获取此值。

If you just want the final number of bytes after the download, it is easiest to check the file size you just write to. 如果您只想在下载后获得最终字节数,则最简单的方法是检查您刚写入的文件大小。

However if you want to display the current progress of how many bytes have been downloaded, you might want to extend apache CountingOutputStream to wrap the FileOutputStream so that everytime the write methods are called it counts the number of bytes passing through and update the progress bar. 但是,如果要显示已下载的字节数的当前进度,可能需要扩展apache CountingOutputStream以包装FileOutputStream以便每次调用write方法时,它会计算通过的字节数并更新进度条。

Update 更新

Here is a simple implementation of DownloadCountingOutputStream . 这是DownloadCountingOutputStream一个简单实现。 I am not sure if you are familiar with using ActionListener or not but it is a useful class for implementing GUI. 我不确定您是否熟悉使用ActionListener ,但它是一个用于实现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));
        }
    }

}

This is the usage sample : 这是用法示例:

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

commons-io has IOUtils.copy(inputStream, outputStream) . commons-ioIOUtils.copy(inputStream, outputStream) So: 所以:

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

IOUtils.copy(is, os);

And IOUtils.toByteArray(is) can be used to get the bytes. 并且IOUtils.toByteArray(is)可用于获取字节。

Getting the total number of bytes is a different story. 获得总字节数是另一回事。 Streams don't give you any total - they can only give you what is currently available in the stream. Streams不会给你任何总数 - 它们只能提供流中当前可用的内容。 But since it's a stream, it can have more coming. 但由于它是一个流,它可以有更多的来。

That's why http has its special way of specifying the total number of bytes. 这就是为什么http有其特殊的方式来指定总字节数。 It is in the response header Content-Length . 它位于响应标头Content-Length So you'd have to call url.openConnection() and then call getHeaderField("Content-Length") on the URLConnection object. 因此,您必须调用url.openConnection() ,然后在URLConnection对象上调用getHeaderField("Content-Length") It will return the number of bytes as string. 它将以字符串形式返回字节数。 Then use Integer.parseInt(bytesString) and you'll get your total. 然后使用Integer.parseInt(bytesString) ,你将得到你的总数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java apache公共FTP,如何将图像文件下载到BufferedImage - Java apache commons FTP, how to download image file to BufferedImage 使用带有 Java 11 的 Apache Commons 4.5.5 上传/下载大文件 - Upload/Download big file with Apache Commons 4.5.5 with Java 11 使用Apache Commons FTPSClient下载0字节文件 - 0 bytes file download with Apache Commons FTPSClient Java:使用Restlet + Apache Commons FileUpload二进制文件上传 - Java: Binary File Upload using Restlet + Apache Commons FileUpload 使用Apache Commons在Java中下载文件时获取HTTP 302 - Getting HTTP 302 when downloading file in Java using Apache Commons 使用apache commons FileUpload的Java Servlet JSP删除文件 - Java Servlet JSP delete file using apache commons FileUpload 使用Apache Commons文件上传 - Using Apache Commons File Upload 无法使用org.apache.commons.io Java库下载pdf网站链接 - Unable to download pdf weblinks using org.apache.commons.io java library 在Java上下载FTP文件夹(使用FTPClient Apache Commons Net 3.6 API) - Download FTP folder on Java (Using FTPClient Apache Commons Net 3.6 API) 使用 Java Apache Commons Net 从与通配符匹配的 FTP 下载文件 - Download a files from FTP matching a wildcard using Java Apache Commons Net
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM