简体   繁体   中英

Download file from server in 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 ?

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

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

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.

Starting with Java 8 you can do it like this:

    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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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