How to download a file in Java?

The following example illustrates how to download a file in Java without using any third party libraries.

DownloadFile.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.

ధన్యవాదాలు (Thanks)

No comments: