用java从服务器下载文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18872611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download file from server in java
提问by Pranjal Choladhara
In my java application I am using the following method to download files from server.
在我的 java 应用程序中,我使用以下方法从服务器下载文件。
public void kitapJar(){
File f = new File("C:/PubApp_2.0/update/lib/kitap.jar");
try{
URL kitap = new URL("http://example.com/update/PubApp_2.0.jar");
org.apache.commons.io.FileUtils.copyURLToFile(kitap, f);
}
catch(IOException ex){
System.out.println("Error...!!");}
}
}
But this download is very slow. How can i make it fast ?
但是这个下载很慢。我怎样才能让它快?
采纳答案by Holger
Starting with Java?7, you can download a file with built-in features as simple as
从 Java?7 开始,您可以下载具有内置功能的文件,就像
Files.copy(
new URL("http://example.com/update/PubApp_2.0.jar").openStream(),
Paths.get("C:/PubApp_2.0/update/lib/kitap.jar"));
// specify StandardCopyOption.REPLACE_EXISTING as 3rd argument to enable overwriting
for earlier versions, the solution from Java?1.4 to Java?6 is
对于早期版本,从 Java?1.4 到 Java?6 的解决方案是
try(
ReadableByteChannel in=Channels.newChannel(
new URL("http://example.com/update/PubApp_2.0.jar").openStream());
FileChannel out=new FileOutputStream(
"C:/PubApp_2.0/update/lib/kitap.jar").getChannel() ) {
out.transferFrom(in, 0, Long.MAX_VALUE);
}
This code transfers a URL content to a file without any 3rd party library. If it's still slow, you know that it is not the additional library's and most probably not Java's fault. At least there's nothing you could improve here. So then you should search the reason outside the JVM.
此代码将 URL 内容传输到没有任何 3rd 方库的文件。如果它仍然很慢,您就知道这不是附加库的错,也很可能不是 Java 的错。至少这里没有什么可以改进的。那么你应该在JVM之外寻找原因。