Java Program to download file from URL.
Objective
Write a Java program to download a file from a direct URL using NIO.
Algorithm / Approach
- Prompt the user for a File URL.
- Extract the filename from the URL string using
substring(). - Create a
URLobject and open aReadableByteChannelfrom its stream. - Open a
FileOutputStreamusing the extracted filename. - Use
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE)to directly stream the data from the internet to the hard drive. - Close the channels.
Download.java
import java.net.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
class Download{
public static void main(String [] ar){
System.out.println("DOWNLOAD MANAGER:");
Scanner sc = new Scanner(System.in);
System.out.print("FileURL: ");
String url = sc.nextLine();
System.out.println("downloading...");
try {
int fnsi = url.lastIndexOf('/');
int end = url.length();
String fname=url.substring(fnsi+1, end);
URL ws = new URL(url);
ReadableByteChannel rbc;
rbc=Channels.newChannel(ws.openStream());
FileOutputStream fos;
fos = new FileOutputStream(fname);
fos.getChannel().transferFrom(rbc,0,Long.MAX_VALUE);
fos.close();
rbc.close();
System.out.print("Download Completed");
}
catch (IOException e){
e.printStackTrace();
}
}
}
Expected Output
FileURL: http://www.prowessapps.in/java.pdf downloading... Download Completed
Explanation of the Program
- Downloading files via standard Byte Streams requires creating a custom loop and an intermediate byte buffer array.
- By using Java NIO Channels, specifically the
transferFrom()method, you instruct the operating system to handle the stream transfer internally. This is drastically faster and requires much less code than legacy stream downloading.
Complexity
Time Complexity
O(n) - Where n is the file size.
Space Complexity
O(1) - Handled internally by NIO.