Saturday, May 24, 2014

How to use Java to download file on internet

At first, I thought I would need to write thousands line of code to download the file on internet. But after studying some article, I found that it is easy to use Commons IO.
Let's start with the sample code below:
package idv.jk.stock;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.io.FileUtils;

public class TestFirst {

 public static void main(String[] args) {
  try
  {
   String strUrl = "<The url of the file>";
   URL source = new URL(strUrl);
   String theStrDestDir = "<The folder you want to put the file>";
   File theStockDest = new File(theStrDestDir);
   FileUtils.forceMkdir(theStockDest);
   
   File destination = new File(theStrDestDir + 
                                   "<the saved filename>");
   
   FileUtils.copyURLToFile(source, destination);
   //File file = new File(".");
   System.out.println("File Downloaded!");
  } catch (MalformedURLException e)
  {
   e.printStackTrace();
  } catch (IOException e)
  {
   e.printStackTrace();
  }
 }

}
Here, let point out something worth mentioning. Also, you can read the API of Commons IO.

At line 21, I used FileUtils.copyURLToFile to build the folder to put the downloaded file. By using the method FileUtils.copyURLToFile, I don't have to worry about if the destination folder and its parent folder exit or not. FileUtils.copyURLToFile will create all the folders.

And the most important, at line 24, is using the method FileUtils.copyURLToFile to download the file from internet.

The first parameter is a URL object(API doc) containing the url of the file and the second is a File object (API doc)representing the directory to put the file.

References

No comments:

Post a Comment