【问题标题】:java - Progress Bar while download with FileUtilsjava - 使用 FileUtils 下载时的进度条
【发布时间】:2016-08-27 02:59:08
【问题描述】:

我正在尝试使用 commons.io Apache 库从 URL 下载一个大文件。 这是我的代码:

    InputStream stream = new URL(CLIENT_URL).openStream();
    ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(null, "Downloading...", stream);
    ProgressMonitor pm = pmis.getProgressMonitor();
    pm.setMillisToDecideToPopup(0);
    pm.setMillisToPopup(0);
    FileUtils.copyInputStreamToFile(pmis, new File(LATEST_FILENAME));
    pmis.close();
    stream.close();

但它不显示弹出窗口。或者说实话,弹窗出现和消失的时间只有一毫秒,而下载大约需要 10 秒。

【问题讨论】:

    标签: java fileutils progressmonitor


    【解决方案1】:

    通用InputStream 不提供有关当前位置或到外部的总长度的信息。见InputStream availiable() 不是 InputStream 的总大小,也没有获取当前位置或获取总大小之类的东西。您也可能只读取流的块/部分,即使进度条也能够计算出流的总长度,它不会知道您只会读取例如 512 个字节。

    ProcessMonitorInputStream 修饰提供的InputStream 并在读取操作期间更新对话框的进度条。默认情况下,ProgressMonitorInputStream 使用传递的availableInputStream 来初始化ProgressMonitor 的最大值。对于某些InputStreams,该值可能是正确的,但在您通过网络传输数据时尤其如此。

    available() 返回估计的字节数 从此输入流中读取(或跳过)而不被 下一次为此输入流调用方法。

    这个初始最大值也是您有时会看到对话框的原因。达到进度条的最大值后,对话框会自动关闭。 为了显示任何有用的信息,您必须以setMinimumsetMaximum 的形式向ProgressMonitor一些关于开始位置和结束位置的提示。

         // using a File just for demonstration / testing
         File f = new File("a");
         try (InputStream stream = new FileInputStream(f)) {
            ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(null, "Downloading...", stream);
            int downloadSize = f.length();
            ProgressMonitor pm = pmis.getProgressMonitor();
            pm.setMillisToDecideToPopup(0);
            pm.setMillisToPopup(0);
            // tell the progress bar that we start at the beginning of the stream
            pm.setMinimum(0);
            // tell the progress bar the total number of bytes we are going to read.    
            pm.setMaximum(downloadSize);
            copyInputStreamToFile(pmis, new File("/tmp/b"));
         }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      相关资源
      最近更新 更多