繁体   English   中英

达到指定的文件大小后,停止HtmlUnit下载

[英]Stop HtmlUnit download after specified file size is reached

达到一定大小后,我一直试图停止使用HtmlUnit启动下载。 InputStream

InputStream input = button.click().getWebResponse().getContentAsStream();

正确下载完整文件。 但是,似乎使用

OutputStream output = new FileOutputStream(fileName);
int bytesRead;
int total = 0;
while ((bytesRead = input.read(buffer)) != -1 && total < MAX_SIZE) {
  output.write(buffer, 0, bytesRead);
  total += bytesRead;
  System.out.print(total + "\n");
}
output.flush();
output.close();
input.close();

以某种方式将文件下载到其他位置(我不知道),完成后将最大大小复制到文件“ fileName”中。 在此过程中不会打印System.out。 有趣的是,在Netbeans中运行调试器并逐步逐步进行时,将打印出总数并得到MAX_SIZE文件。

在1024到102400之间的范围内更改缓冲区大小没有任何区别。

我也尝试过下议院

BoundedInputStream b = new BoundedInputStream(button.click().getWebResponse().getContentAsStream(), MAX_SIZE);

没有成功。

这个已有2. 5年历史的职位 ,但是我不知道如何实现建议的解决方案。

为了停止在MAX_SIZE处的下载,我缺少什么吗?

(为简洁起见,省略了异常处理等)

无需为此使用HTMLUnit。 实际上,将其用于如此简单的任务是一个非常过分的解决方案,并且会使速度变慢。 我能想到的最好方法是:

final String url = "http://yoururl.com";
final String file = "/path/to/your/outputfile.zip";
final int MAX_BYTES = 1024 * 1024 * 5;  // 5 MB

URLConnection connection = new URL(url).openConnection();
InputStream input = connection.getInputStream();
byte[] buffer = new byte[4096];
int pendingRead = MAX_BYTES;
int n;
OutputStream output = new FileOutputStream(new File(file));
while ((n = input.read(buffer)) >= 0 && (pendingRead > 0)) {
    output.write(buffer, 0, Math.min(pendingRead, n));
    pendingRead -= n;
}
input.close();
output.close();

在这种情况下,我将最大下载大小设置为5 MB,缓冲区设置为4 KB。 该文件将在while循环的每次迭代中写入磁盘,这似乎正是您想要的。

当然,请确保您处理了所有必需的异常(例如: FileNotFoundException )。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM