【问题标题】:Is this the best way to download a file in java?这是在java中下载文件的最佳方式吗?
【发布时间】:2011-06-09 11:51:00
【问题描述】:
public void download(String url, String destination) {
        BufferedOutputStream localBufferedOutputStream = null;
        URLConnection localURLConnection = null;
        InputStream localInputStream = null;
        try {
            URL localURL = new URL(url);

            localBufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destination));
            localURLConnection = localURL.openConnection();
            localInputStream = localURLConnection.getInputStream();

            byte[] arrayOfByte = new byte[1024];
            int i;
            while ((i = localInputStream.read(arrayOfByte)) != -1) {
                localBufferedOutputStream.write(arrayOfByte, 0, i);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (localInputStream != null) {
                    localInputStream.close();
                }
                if (localBufferedOutputStream != null) {
                    localBufferedOutputStream.close();
                }
            } catch (IOException localIOException3) {
                System.out.println(localIOException3);
            }
        }
    }

我正在调试我的应用程序,它似乎有点慢。我想知道这是否是我的互联网。这是在java中下载文件的正确方法吗?文件大小为 26mb。

【问题讨论】:

  • 当您从网络浏览器下载同一个文件时会发生什么?
  • 喜欢 Java:如此精确且不冗长的语言

标签: java download


【解决方案1】:

这当然不是最好的方法。丢弃所有异常的代码很少是做任何事情的最佳方式。您也可以考虑不使用字符串作为参数。 URI 和 File 是不错的选择。

如果你想复制流 transferTo 是一个好方法。

【讨论】:

    【解决方案2】:

    您可以省略BufferedOutputStream,因为您自己已经在使用缓冲区。但这不会有很大的不同。

    可能(或可能不会)产生重大影响的是using the nio channel classes,而不是流。

    【讨论】:

    • 你可以使用更大的缓冲区,例如8192.
    【解决方案3】:

    您应该始终查看诸如 Apache 之类的库。他们为您完成了所有艰苦的工作: http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html

    我用

    static String   readFileToString(File file)
              Reads the contents of a file into a String using the default encoding for the VM.
    

    很多。

    如果您知道自己有一个 URL(以及流),请查看: http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html

    【讨论】:

    • copyURLToFile 比流更好?还是它本身就是一个流?
    • 使用默认编码是个糟糕的主意,尤其是在这种情况下。这意味着数据将以不同方式损坏,具体取决于程序运行的平台。
    【解决方案4】:

    作为替代方案,仅供参考,您可以研究 HTMLUnit。即使在存在浏览器重定向的网站上,此框架也允许您下载文件。

    http://htmlunit.sourceforge.net/

    【讨论】:

    • 好久没问这个了。 xD 谢谢詹姆斯的回答。我记得走阿帕奇的方式。我记得最近检查了 htmlunit,发现它在页面上执行了 javascript,非常棒。谢谢
    • 很高兴听到您取得了一些进步。顺便说一句,您是否进行过文件完整性测试和处理下载中断之类的事情?另外,这可能很有趣:stackoverflow.com/questions/4687615/…
    • 我没有。我记得尝试停止/恢复下载,有人建议我查看 jdownloader 源代码,但我从来没有这样做过。感谢您提供该资源。
    猜你喜欢
    • 2010-11-24
    • 2019-03-05
    • 2014-01-30
    • 2016-03-06
    • 2019-08-12
    • 2011-12-30
    • 2017-08-23
    • 2021-05-15
    • 2012-10-22
    相关资源
    最近更新 更多