Thursday 14 November 2013

How to download a file in Java?

The following example illustrates how to download a file in Java.

import java.net.*;
import java.io.*;
class DownloadFile
{
    public static void main(String args[]) throws Exception
    {
        // Get url
        URL u=new URL(args[0]);
       
        // Open connection first
        HttpURLConnection con=(HttpURLConnection)u.openConnection();
       
        // Get the input stream pointing to the file
        InputStream fin=con.getInputStream();
       
        // Create FileOutputStream to write to a file
        FileOutputStream fout=new FileOutputStream(args[1]);
       
        int k;
       
            // Loop till end of file
            while((k=fin.read())!=-1)
            {
                // Write each byte into file
                fout.write(k);
            }
       
        // close all
        fin.close();
        fout.close();
    }
}
openConnection(): This method opens a connection to the given file.
getInputStream(): Returns the java.io.InputStream object with which we can read data from the file and download it.

No comments:

Post a Comment