小编xuq*_*019的帖子

使用java在网站上下载文件的最快方法

我正在编写一个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();
}
Run Code Online (Sandbox Code Playgroud)

java url

2
推荐指数
1
解决办法
2459
查看次数

标签 统计

java ×1

url ×1