Java download file

Often it is required to download a file directly from a URL and save to a directory on local system such as downloading a file from a remote repository. This requires reading a file from url and writing it to a local file.
This article will share different methods to download a file from URL in java. Methods defined here are applicable to all types of file such as a pdf file, an exe file, a txt file or a zip file etc.

Method 1: Using Java IO
Traditional java.io package contains classes for reading and writing to a stream. These classes can be used to read a file using input stream and write its contents to an output stream.

This approach is based on the following steps.

  1. Create a connection to the given file url.
  2. Get input stream from the connection. This stream can be used to read file contents.
  3. Create an output stream to the file to be downloaded.
  4. Read the contents from the input stream and write to the output stream.

Java code to download file from URL with this method is given below.

import java.net.URL; 
import java.net.URLConnection; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 

public class FileDownloader { 
  public static void main(String[] args) { 
    OutputStream os = null; 
    InputStream is = null; 
    String fileUrl = "http://200.34.21.23:8080/app/file.txt"; 
    String outputPath = "E:\\downloads\\downloaded.txt"; 
    try { 
      // create a url object 
      URL url = new URL(fileUrl); 
      // connection to the file 
      URLConnection connection = url.openConnection();  
      // get input stream to the file 
      is = connection.getInputStream(); 
      // get output stream to download file 
      os = new FileOutputStream(outputPath); 
      final byte[] b = new byte[2048]; 
      int length; 
      // read from input stream and write to output stream 
      while ((length = is.read(b)) != -1) { 
        os.write(b, 0, length); 
      } 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } finally { 
      // close streams 
      if (os != null) 
        os.close(); 
      if (is != null) 
        is.close(); 
    } 
  } 
}

Remember that the output and input paths should end with the file name else there will be an error.

All the methods in this post read a file at a remote URL. If you want to read a file at local system, then refer this post.

Method 2: Using Java NIO
Follow below steps to download a file using Java NIO.

  1. Create an input stream to the file to be downloaded.
  2. Create a new channel that will read data from this input stream.
  3. Create an output stream that will write file contents after reading it from the channel created in Step 2.
  4. Get the channel from this output stream and write the contents from channel created in Step 2.

You will understand the algorithm better after looking at the below code example.

import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.URL; 
import java.nio.channels.Channels; 
import java.nio.channels.ReadableByteChannel; 
import java.io.File; 

public class FileDownloader { 
  public static void main(String[] args) { 
    try { 
      String fileUrl = "http://200.34.21.23:8080/app/file.pdf"; 
      String outputPath = "E:\\downloads\\downloaded.pdf"; 
      URL url = new URL(fileUrl); 
      // create an input stream to the file InputStream 
      inputStream = url.openStream(); 
      // create a channel with this input stream 
      ReadableByteChannel channel = Channels.newChannel( url.openStream()); 
      // create an output stream 
      FileOutputStream fos = new FileOutputStream( new File(outputPath)); 
      // get output channel, read from input channel and write to it 
      fos.getChannel().transferFrom(channel, 0, Long.MAX_VALUE); 
      // close resources 
      fos.close(); 
      channel.close(); 
    } catch(IOException e) { 
      e.printStackTrace(); 
    } 
  } 
}

Note that transferFrom() method of a channel takes 3 arguments.
1. input file channel,
2. position at which it will start reading the file, 0 here means the beginning of file, and
3. number of bytes that will be transferred at one time. This value is set to a very large value(Long.MAX_VALUE) for higher efficiency.

Learn different methods of writing to a file here.

Method 3: Using Apache Commons IO Library
Apache Commons IO Library has a org.apache.commons.io.FileUtils class which contains a method copyURLToFile().

This method takes two arguments:
1. java.net.URL object pointing to the source file, and
2. java.io.File object which points to an output file path.

Remember that both paths should contain the name of file at the end and output path should be a location on local system at which the file will be downloaded.
copyURLToFile() reads the file from remote location and copies it to the local machine. Example,

import org.apache.commons.io.FileUtils; 

public class FileDownloader { 
  public static void main(String[] args) { 
    String fileUrl = "http://200.34.21.23:8080/app/file.zip"; 
    String outputPath = "E:\\downloads\\downloaded.zip"; 
    FileUtils.copyURLToFile(new URL(fileUrl), new File(outputPath)); 
  } 
}

You can add Apache Commons IO dependency to your project as per the build tool.

<!– Maven –>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>

// Gradle
compile group: ‘org.apache.commons’, name: ‘commons-io’, version: ‘1.3.2’

Hope the article was useful in explaining different ways to download a file from URL in java.
Do not forget to click the clap below.