在java中下载文件时进度条冻结 [英] Progress bar freezing while downloading file in java
本文介绍了在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("http://assets.minecraft.net/"+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:
这篇关于在java中下载文件时进度条冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文