本文介绍了在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中下载文件时进度条冻结
发布评论