The following example illustrates how to download a file in Java.
getInputStream(): Returns the java.io.InputStream object with which we can read data from the file and download it.
openConnection(): This method opens a connection to the given file.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();
}
}
getInputStream(): Returns the java.io.InputStream object with which we can read data from the file and download it.