微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Java 从 URL 下载文件的更快方法是什么

如何解决使用 Java 从 URL 下载文件的更快方法是什么

我在互联网上搜索过(可能是我没有使用正确的关键字)从未找到使用 java 从 URL 下载文件的更快方法的答案

这是我的代码我可以做得更好以获得更好的性能

import java.io.FileOutputStream;
import java.math.BigInteger;
import java.io.IOException;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardcopyOption;
import java.nio.file.Files.*;
import java.io.InputStream;
import java.net.URL;
 import java.net.URI;
import java.nio.file.Paths;
    
public class download_example2 {
 
    public static void download(String link,String savepath)
            throws IOException {
            
     String file_name="";
 
         try{
             file_name=Paths.get(new URI(link).getPath()).getFileName().toString();
            }
    
        catch(Exception e){System.out.println(e);}
    
          savepath = savepath+File.separator+file_name;
                 
         InputStream input_stream = new URL(link).openStream();
           
           int size=input_stream.available();
     
       System.out.println("\nUsing Files.copy()\nFile size = "+size+" Bytes\nDownload started");
   
     Files.copy(input_stream,Paths.get(savepath),StandardcopyOption.REPLACE_EXISTING);
            input_stream.close();
             

            System.out.println("\nFile downloaded"); 
        } 
    

    public static void main(String[] args) {
        String link = "https://redirector.gvt1.com/edgedl/android/studio/install/4.1.3.0/android-studio-ide-201.7199119-cros.deb";
        String savepath = "D:/Download";
        try {

        int t=5,avg=0;
        while(t-->0)
           {
            long start = System.currentTimeMillis();
                    new download_example2().download(link,savepath); //download() method call
            long end = System.currentTimeMillis();

            System.out.println("Time taken for download "+(end-start)+" ms\n---------------------------------\n");

            avg+=(end-start)/1000;
            }

         System.out.println("\nAverage time taken : "+(avg/5)+"seconds");

        } catch (IOException e) {
            e.printstacktrace();
        }
    }
}

还有比这更好的方法吗?请告诉比这更好的方法

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?