简体   繁体   English

用java从服务器下载文件

[英]Download file from server in java

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 ?我怎样才能让它快?

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.此代码将 URL 内容传输到没有任何 3rd 方库的文件。 If it's still slow, you know that it is not the additional library's and most probably not Java's fault.如果它仍然很慢,您就知道这不是附加库的错,也很可能不是 Java 的错。 At least there's nothing you could improve here.至少这里没有什么可以改进的。 So then you should search the reason outside the JVM.那么你应该在JVM之外寻找原因。

Starting with Java 8 you can do it like this:从 Java 8 开始,您可以这样做:

    ReadableByteChannel readChannel = Channels.newChannel(new URL("http://example.com/update/PubApp_2.0.jar").openStream());
    FileOutputStream fileOS = new FileOutputStream("C:\\PubApp_2.0\\update\\lib\\kitap.jar");
    FileChannel writeChannel = fileOS.getChannel();
    writeChannel
            .transferFrom(readChannel, 0, Long.MAX_VALUE);

This should be fast!这应该很快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM