用java从服务器下载文件 [英] Download file from server in java

查看:31
本文介绍了用java从服务器下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 java 应用程序中,我使用以下方法从服务器下载文件.

In my java application I am using the following method to download files from server.

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 ?

推荐答案

从 Java 7 开始,您可以像下载具有内置功能的文件一样简单

Starting with Java 7, you can download a file with built-in features as simple as

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

对于早期版本,从 Java 1.4 到 Java 6 的解决方案是

for earlier versions, the solution from Java 1.4 to Java 6 is

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

此代码将 URL 内容传输到没有任何 3rd 方库的文件.如果它仍然很慢,您就知道这不是附加库的错,也很可能不是 Java 的错.至少这里没有什么可以改进的.那么你应该在JVM之外寻找原因.

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.

这篇关于用java从服务器下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆