我正在编写一个 Java 代码以使用 http 协议在站点上下载大量 zip 文件,每个文件的大小约为 1MB(1024KB)。
我知道有很多方法可以做到这一点。我只是在徘徊哪个是最快的,我想知道每次下载的进度,比如显示百分比数字之类的。
我只是给出我的代码版本,关于如何改进它的任何想法?
谢谢大家。
public static void downloadFile(String downloadUrl , String fileName) throws Exception {
URL url=new URL(downloadUrl);
URLConnection connection = url.openConnection();
int filesize = connection.getContentLength();
float totalDataRead=0;
java.io.BufferedInputStream in = new java.io.BufferedInputStream(connection.getInputStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(fileName);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int i=0;
while((i=in.read(data,0,1024))>=0) {
totalDataRead=totalDataRead+i;
bout.write(data,0,i);
float Percent=(totalDataRead*100)/filesize;
System.out.println((int)Percent);
}
bout.close();
in.close();
}