Java获取下载进度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22273045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java getting download progress
提问by deejay31
I am writing a Java application (Using NetBeans as an IDE and a jFrame form), and one part of it downloads a file. How can I update a progress bar with the current progress of the download, or at least get the total amount of currently downloaded bytes in another thread?
我正在编写一个 Java 应用程序(使用 NetBeans 作为 IDE 和一个 jFrame 表单),它的一部分下载了一个文件。如何使用当前下载进度更新进度条,或者至少获取另一个线程中当前下载的总字节数?
Below is a part of my code:
下面是我的代码的一部分:
Runnable updatethread = new Runnable() {
public void run() {
try {
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL("server/package.zip").openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream("package.zip");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int x=0;
while((x=in.read(data,0,1024))>=0)
{
bout.write(data,0,x);
}
bout.close();
in.close();
}
catch(FileNotFoundException e) { } catch (IOException e) { }
}
};
new Thread(updatethread).
start();
try {
updatethread.wait();
} catch (InterruptedException ex) { }
采纳答案by slartidan
A working example, using your code and displaying the progress in a progress bar could look like this:
一个工作示例,使用您的代码并在进度条中显示进度可能如下所示:
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class Progressbar {
public static void main(String[] args) {
final JProgressBar jProgressBar = new JProgressBar();
jProgressBar.setMaximum(100000);
JFrame frame = new JFrame();
frame.setContentPane(jProgressBar);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(300, 70);
frame.setVisible(true);
Runnable updatethread = new Runnable() {
public void run() {
try {
URL url = new URL("http://downloads.sourceforge.net/project/bitcoin/Bitcoin/blockchain/bitcoin_blockchain_170000.zip");
HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
long completeFileSize = httpConnection.getContentLength();
java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(
"package.zip");
java.io.BufferedOutputStream bout = new BufferedOutputStream(
fos, 1024);
byte[] data = new byte[1024];
long downloadedFileSize = 0;
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
downloadedFileSize += x;
// calculate progress
final int currentProgress = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 100000d);
// update progress bar
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
jProgressBar.setValue(currentProgress);
}
});
bout.write(data, 0, x);
}
bout.close();
in.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
new Thread(updatethread).
start();
}
}
This shows how to do it - before using it you should think about GUI-Threads, etc.
这显示了如何做到这一点 - 在使用它之前,您应该考虑 GUI-Threads 等。
回答by Jazzepi
I had a similar problem with doing a progress bar for uploads, but the solution is basically the same; create a new CountingOutputStream
that extends FileOutputStream
and takes a listener that can listen to the bytes as they're written. You can see the OutputStreamProgress class as an example in the link below.
我在做上传进度条时遇到了类似的问题,但解决方案基本相同;创建一个新的CountingOutputStream
扩展FileOutputStream
并接受一个侦听器,该侦听器可以在写入字节时进行侦听。您可以在下面的链接中查看 OutputStreamProgress 类作为示例。
How to get a progress bar for a file upload with Apache HttpClient 4?
如何使用 Apache HttpClient 4 获取文件上传的进度条?
It looks like Apache commons IO already has a class that does something similar. This isn't exactly the same thing. You have to poll the OutputStream to find out where it's at, where-as in the solution I provided with the listener, the callbacks are being updated continuously.
看起来 Apache commons IO 已经有一个类做了类似的事情。这不是完全一样的事情。您必须轮询 OutputStream 以找出它所在的位置,就像我提供给侦听器的解决方案一样,回调正在不断更新。
You can get it through maven, or downloading the jar through their website.
您可以通过 maven 获取它,或者通过他们的网站下载 jar。
Maven -> http://mvnrepository.com/artifact/commons-io/commons-io
Maven -> http://mvnrepository.com/artifact/commons-io/commons-io
Jar -> http://commons.apache.org/proper/commons-io/download_io.cgi
Jar -> http://commons.apache.org/proper/commons-io/download_io.cgi
回答by Jiang
URL url = new URL(urlString);
HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
long fileSize = httpConnection.getContentLength();
Notice that the content-length
is provided by the server in Http Header
.
请注意,content-length
由 中的服务器提供Http Header
。
API for the function getContentLength()
:
函数API getContentLength()
:
int java.net.URLConnection.getContentLength()
Returns the value of the content-length header field.
Returns:
the content length of the resource that this connection's URL references, or -1 if the content length is not known.
int java.net.URLConnection.getContentLength()
返回内容长度头字段的值。
返回:
此连接的 URL 引用的资源的内容长度,如果内容长度未知,则为 -1。