0

I have searched over internet(may be I am not using correct keywords) never found answer for faster way to download file from URL using java

This is my code Can I do better to achieve better performance over this

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();
        }
    }
}

is there any better way than this. please tell the better way than this

7575 mohan
  • 21
  • 5

0 Answers0