如何解决使用 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 举报,一经查实,本站将立刻删除。