我正在尝试用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秒钟左右。
发布于 2016-07-28 16:24:42
一般的InputStream不向外部提供有关当前位置或总长度的信息。请参见InputStream availiable()不是InputStream的总大小,也没有get当前位置或get总大小这样的东西。您还可能只读取流的块/部分,甚至进度条也能够计算出流的总长度--它不会知道您只读取512字节。
ProcessMonitorInputStream在读取操作期间装饰提供的InputStream并更新对话框的进度条。默认情况下,ProgressMonitorInputStream使用传递的InputStream的available来初始化ProgressMonitor的最大值。对于某些InputStreams,这个值可能是正确的,但特别是当您通过网络传输数据时。
available()返回可以从该输入流中读取(或跳过)的字节数的估计值,而不会在下一次调用该输入流的方法时阻塞。
这个初始值也是您有时看到对话框的原因。到达进度条的最大值后,对话框将自动关闭。为了显示任何有用的东西,您必须以setMinimum和setMaximum的形式给出一些关于开始位置和结束位置的提示。
// 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"));
}https://stackoverflow.com/questions/36980851
复制相似问题