在java中下载文件时进度条冻结

编程入门 行业动态 更新时间:2024-10-24 10:17:49
本文介绍了在java中下载文件时进度条冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能的重复:JProgressBar 不会更新

所以我试图显示正在用 Java 下载的文件的下载进度.我可以将当​​前百分比作为字符串输出到控制台,但是当我尝试更新 UI 时,它会冻结,直到下载完成.

So I am trying to show the download progress of a file being downloaded in Java. I can output the current percentage as a String to the console, but when I try to update the UI, it freezes until the download is complete.

public void downloadFile(String fileName) { try { long startTime = System.currentTimeMillis(); System.out.println("Connecting to site...\n"); URL url = new URL("assets.minecraft/"+fileName+"/minecraft.jar"); URLConnection connection = url.openConnection(); try (InputStream reader = url.openStream(); FileOutputStream writer = new FileOutputStream("minecraft.jar")) { byte[] buffer = new byte[153600]; int totalBytesRead = 0; int bytesRead = 0; int totalSize = connection.getContentLength(); jProgressBar1.setMaximum(totalSize); System.out.println("Downloading\n"); while ((bytesRead = reader.read(buffer)) > 0) { writer.write(buffer, 0, bytesRead); buffer = new byte[153600]; totalBytesRead += bytesRead; jProgressBar1.setValue(totalBytesRead); System.out.println(totalBytesRead*100/totalSize+"% complete"); } long endTime = System.currentTimeMillis(); System.out.println("Done. " + (new Integer(totalBytesRead).toString()) + " bytes read (" + (new Long(endTime - startTime).toString()) + " millseconds).\n"); } } catch (MalformedURLException e) { } catch (IOException e) { } }

我在某处读到您需要使用另一个线程,但我无法成功做到这一点.

I read somewhere that you need to use another thread but I was unable to successfully do that.

推荐答案

一种选择是使用 SwingWorker.以下是一些您可以考虑的有用答案:

One option would be using SwingWorker. Here are some useful answers you may consider:

  • 复制目录和文件时需要有JProgress栏来衡量进度
  • SwingWorker 的工作原理

更多推荐

在java中下载文件时进度条冻结

本文发布于:2023-11-26 07:07:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633125.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:进度条   文件   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!