使用java apache commons下载文件?

使用java apache commons下载文件?,java,apache-commons-io,Java,Apache Commons Io,如何使用库下载文件并打印保存的字节?我试着用 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("\\",

如何使用库下载文件并打印保存的字节?我试着用

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);
        }
    }
但我无法显示字节或进度条。我应该使用哪种方法

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);
        }
    }
有。因此:

IOUtils.toByteArray(is)
可用于获取字节

获取字节总数是另一回事。流不会给你任何总数-它们只能给你流中当前可用的数据。但既然它是一条小溪,它可以有更多的来


这就是为什么http有其特殊的方式来指定总字节数。它位于响应标题
内容长度
中。因此,您必须调用
url.openConnection()
,然后在
URLConnection
对象上调用
getHeaderField(“内容长度”)
。它将以字符串形式返回字节数。然后使用
Integer.parseInt(bytesString)
就可以得到总字节数。

如果您想在下载前获得总字节数,可以从http响应中的
内容长度
头中获得该值

如果您只需要下载后的最终字节数,最简单的方法是检查您刚刚写入的文件大小

但是,如果要显示下载字节数的当前进度,可能需要扩展apache
CountingOutputStream
来包装
FileOutputStream
,以便每次调用
write
方法时,它都会计算通过的字节数并更新进度条

更新

下面是下载计数输出流的一个简单实现。我不确定您是否熟悉使用
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));
        }
    }

}
这是使用示例:

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

隐马尔可夫模型。。有没有办法显示从该流下载的字节?我在看,但我看不到路。谢谢你的回复。顺便说一句,字节本身,还是它们的计数?下载的总字节数,如果这是计数的意思?对不起,我对java还是新手。太棒了。谢谢你,我希望我可以得到这个工作,以显示当前下载的标签字节!我如何扩展apache以使用它?fl=新文件(System.getProperty(“user.home”)。替换(“\\”,“/”+“/Desktop/Screenshots.zip”);dl=新URL(“);OutputStream os=新文件OutputStream(fl);InputStream is=dl.openStream();CountingOutputStream count=新CountingOutputStream(os);dl.openConnection().getHeaderField(“内容长度”);IOUtils.copy(is,os);//开始传输我做得对吗?你介意在你的问题后面加上上面的代码吗?这很难理解。我会尽力帮助你。@Kyle更新了。我希望你喜欢答案。顺便说一句,dl.openConnection()将打开一个新的连接以及dl.openStream()。您应该重新使用连接,而不是再次打开连接,因为如果动态生成目标的内容,您可能会得到不同的内容长度。哇,非常感谢!我印象深刻!我有一个关于进度条的小问题。我是否通过progressBar.setValue设置进度条的值?如果是,我在访问d时遇到问题拥有已加载的字节,并将该值从内容长度中转换为百分比。我真的不喜欢在你制作了这个漂亮的片段后问这样愚蠢的问题。我很感激。(我试图做的是从已下载的字节中减去内容长度,然后只做数学运算以获得%来设置进度条。这是正确的方法吗?)
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);
        }
    }
}