Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file from server in java

Tags:

java

download

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 ?

like image 577
Pranjal Choladhara Avatar asked Sep 18 '13 12:09

Pranjal Choladhara


People also ask

How do I download a text file in Java?

We will use the copy(inputStream, fileOS) method to download a file into the local system. InputStream inputStream = new URL("http://example.com/my-file-path.txt").openStream(); FileOutputStream fileOS = new FileOutputStream("/Users/username/Documents/file_name. txt"); int i = IOUtils. copy(inpuStream, fileOS);


1 Answers

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.

like image 102
Holger Avatar answered Nov 03 '22 04:11

Holger