简体   繁体   English

在不使用 RAM 的情况下从 Internet 下载文件并显示进度条

[英]Download a file from internet without using RAM and show a progress bar

I realize there are several ways to download a file via internet (http)我意识到有几种方法可以通过互联网(http)下载文件

If a URL for the file is ( http://hoge.com/foo.dat ), a starting point would be:如果文件的 URL 是( http://hoge.com/foo.dat ),则起点是:

new URL("http://hoge.com/foo.dat").openStream();

and choose how to handle the stream.并选择如何处理 stream。

As far as I understand, using BufferedReader is one of ways to download it and provide values to show a progress bar of the downloading.据我了解,使用BufferedReader是下载它并提供值以显示下载进度条的方法之一。 However, it uses RAM (if it is not correct, I am happy though..).但是,它使用 RAM(如果不正确,我很高兴..)。

I find that there is a way to download without using RAM as below:我发现有一种方法可以在不使用 RAM 的情况下进行下载,如下所示:

new FileOutputStream("foo.dat").getChannel()
.transferFrom(
Channels.newChannel(new URL("http://hoge.com/foo.dat").openStream()),
0, Long.MAX__VALUE
);

But in this case, I cannot see the progress to show in the progress bar.但在这种情况下,我看不到进度条中显示的进度。

Please tell me how to download a file and show the progress without using RAM.请告诉我如何在不使用 RAM 的情况下下载文件并显示进度。

Download a file from internet without using RAM在不使用 RAM 的情况下从 Internet 下载文件

This is a hazy specification.这是一个模糊的规范。 Any download will temporariely use at least tiny amounts of memory.任何下载都会暂时使用至少少量的 memory。 This is almost unavoidable, unless you find a way to directly stream bytes from the network card to a file storage like a hard drive.这几乎是无法避免的,除非你找到一种方法,直接将 stream 字节从网卡存储到硬盘之类的文件存储中。 However, even those usually have an internal memory to store data, before write operations can be executed.然而,即使是那些通常有一个内部 memory 来存储数据,在执行写操作之前。

If you want to avoid using a lot of RAM space, then streaming a file is the correct way to do it.如果您想避免使用大量 RAM 空间,那么流式传输文件是正确的方法。 The BufferedReader you are using does not store the entire file to RAM memory, but only the portion that has already arrived, but not yet written to the target.您正在使用的BufferedReader不会将整个文件存储到 RAM memory,而只会存储已经到达但尚未写入目标的部分。 So unless your output (hard drive) is blocking, or slow, the memory usage will be low.因此,除非您的 output(硬盘驱动器)阻塞或缓慢,否则 memory 的使用率会很低。

If however your output channel is slow or blocking, then your memory might run up.但是,如果您的 output 通道很慢或阻塞,那么您的 memory 可能会运行。

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

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