Java 进度条帮助

发布于 2024-10-23 17:48:05 字数 201 浏览 1 评论 0原文

我需要为以下任务延迟实现一个进度条

FileOutputStream Fos= new FileOutputStream(FilePath);
byte buffer[]=Services.downloadFile(FilePath);
Fos.write(buffer);

现在,我如何知道文件已下载了多少来更新进度条

I need to implement a progress bar for the following task delay

FileOutputStream Fos= new FileOutputStream(FilePath);
byte buffer[]=Services.downloadFile(FilePath);
Fos.write(buffer);

Now, how can i know how much the file has been downloaded to update the progress bar

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

辞旧 2024-10-30 17:48:05

这并不容易,因为 Services.downloadFile() 不会以块的形式提供文件。如果你有一个循环,那就很简单了。

如果你可以改变API,我建议这样改变:

Services.downloadFile(File, OutputStream);

并让downloadFile()将文件写入流中。现在,您可以包装流并通过重载各个版本的 write() 来计算写入的字节数。

[编辑]我看到Services是一个RMI代理。在这种情况下,你不能使用上面的方法。相反,它变得更加复杂:

您的服务器上需要一个下载池(想想“地图”)。该池允许您为每次下载请求另一个数据块。

因此,在您的服务器上,您需要:

  1. 创建一个处理下载的对象,该对象具有 byte[] read() 方法。
  2. 使用键将对象放入地图中。以某种方式将密钥发送给客户端。
  3. 对于每个对象,创建一个实际下载数据并将数据添加到缓冲区的线程。 read() 方法返回缓冲区的内容并将其清除。

在客户端:

  1. 您需要调用服务器上的方法来创建新的下载对象并启动下载线程。
  2. 现在您需要一个循环来调用服务器上下载对象的read()。该 API 类似于 read(key),服务器在映射中查找密钥,然后对下载对象调用 read()
  3. 将读取调用的结果写入文件时显示进度

That's not easy since Services.downloadFile() doesn't give you the file in chunks. If you had a loop, it would be simple.

If you can change the API, I suggest to change it in this way:

Services.downloadFile(File, OutputStream);

and let downloadFile() write the file into the stream. Now you can wrap the stream and count the bytes written by overloading the various versions of write().

[EDIT] I saw that Services is an RMI proxy. In this case, you can't use the approach above. Instead it gets more complex:

You need a pool of downloads on your server (think "Map"). The pool allows you to request another block of data for each download.

So on your server, you need:

  1. Create an object that handles the download and which has a byte[] read() method.
  2. Put the objects into a map with a key. Send the key to the client somehow.
  3. For each object, create a thread that actually downloads the data and adds the data to a buffer. The read() method returns the content of the buffer and clears it.

On the client:

  1. You need to call a method on the server to create a new download object and start the download thread.
  2. Now you need a loop that calls read() on the download object on the server. The API is something like read(key), the server looks up the key in the map and then calls read() on the download object.
  3. Show the progress as you write the result of the read calls to the file
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文