Open In App

File Download Manager System in Java

Last Updated : 10 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A file download manager system allows us to download files from the internet to a local directory. This system can handle multiple downloads, improve download speed, and also manage the download process in a structured way.

In this article, we will build a file download manager system in Java using multiple classes, interfaces, and threads to handle the downloads concurrently. This project will help beginners understand Java programming concepts like multithreading, input/output operations, and URL handling.

Working of the File Download Manager System

Here is how our download manager system is going to work:

  • The user provides a list of file URLs to download.
  • Each download task will be processed concurrently using multiple threads.
  • The system will check if the URL is valid before initiating the download.
  • The file will be downloaded to the specified directory.
  • The system will report the success or failure of each download.

Project Structure

The image below demonstrates the project structure

ProjectStructure


We will organize the code into these parts which are listed below:

  • DownloadTask: This class implements the callable interface to represent a download task.
  • DownloadUtils: This class provides utility methods for validating URLs, downloading files, and verifying directories.
  • DownloadManager: This class manages the execution of multiple download tasks concurrently.
  • Main: This class is the entry point to initiate the download process.

Let's now try to implement the code.

Java File Download Manager System Project Implementation

1. DownloadTask Class

This class is used to represents an individual download task and also handles the actual file downloading process. It implements the Callable interface to allow execution of tasks using threads. This class is also responsible for handling the download logic for each file, such as starting the download, simulating download progress, and returning the status of the download.

DownloadTask.java:

Java
package com.downloader;

import java.util.concurrent.Callable;

public class DownloadTask implements Callable<String> {
    private String fileUrl;
    private String destination;

    public DownloadTask(String fileUrl, String destination) {
        this.fileUrl = fileUrl;
        this.destination = destination;
    }

    @Override
    public String call() throws Exception {
        System.out.println("Starting download from: " + fileUrl);
        try {
            Thread.sleep(3000); // Simulating download time
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return "Download interrupted for " + fileUrl;
        }
        System.out.println("Download completed for: " + fileUrl);
        return "Download successful for " + fileUrl;
    }
}


2. DownloadUtils Class

This class is a utility class that provides various helper methods used in the file download process. This class handles URL validation, file downloading, and directory verification.

DownloadUtils.java:

Java
package com.downloader;

import java.io.*;
import java.net.*;
import java.nio.file.*;

public class DownloadUtils {

    /**
     * Validates the given URL to check if it's a valid and accessible URL.
     *
     * @param urlString The URL to validate.
     * @return true if the URL is valid, false otherwise.
     */
    public static boolean isValidUrl(String urlString) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD"); // Only check the headers (no body)
            connection.setConnectTimeout(5000); // Set timeout to 5 seconds
            connection.setReadTimeout(5000);
            int responseCode = connection.getResponseCode();
            return (responseCode == HttpURLConnection.HTTP_OK);
        } catch (MalformedURLException e) {
            System.err.println("Invalid URL: " + urlString);
            return false;
        } catch (IOException e) {
            System.err.println("Error checking URL: " + e.getMessage());
            return false;
        }
    }

    /**
     * Downloads a file from a URL and saves it to the specified destination.
     *
     * @param fileUrl      The URL of the file to download.
     * @param destination  The file path to save the downloaded file.
     * @throws IOException if an I/O error occurs during downloading.
     */
    public static void downloadFile(String fileUrl, String destination) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000); // Set timeout to 5 seconds
        connection.setReadTimeout(5000);

        try (InputStream in = connection.getInputStream();
             FileOutputStream out = new FileOutputStream(destination)) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }

        System.out.println("File downloaded to: " + destination);
    }

    /**
     * Verifies if the destination directory exists. If it doesn't, it creates the directory.
     *
     * @param directoryPath The path to the directory.
     * @return true if the directory exists or was successfully created, false otherwise.
     */
    public static boolean verifyDirectory(String directoryPath) {
        Path path = Paths.get(directoryPath);
        if (!Files.exists(path)) {
            try {
                Files.createDirectories(path);
                System.out.println("Directory created: " + directoryPath);
                return true;
            } catch (IOException e) {
                System.err.println("Failed to create directory: " + e.getMessage());
                return false;
            }
        }
        return true;
    }
}


3. DownloadManager Class

This class is the heart of the download manager system. It is responsible for managing multiple concurrent download tasks and executing them in parallel using a fixed thread pool.

DownloadManager.java:

Java
package com.downloader;

import java.util.concurrent.*;
import java.util.*;

public class DownloadManager {

    private static final int NUM_THREADS = 4;
    private ExecutorService executorService;

    public DownloadManager() {
        executorService = Executors.newFixedThreadPool(NUM_THREADS);
    }

    public void startDownload(String[] fileUrls, String destination) {
        List<Callable<String>> tasks = new ArrayList<>();
        for (String fileUrl : fileUrls) {
            tasks.add(new DownloadTask(fileUrl, destination));
        }

        try {
            List<Future<String>> results = executorService.invokeAll(tasks);
            for (Future<String> result : results) {
                try {
                    System.out.println(result.get());
                } catch (ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }

    public static void main(String[] args) {
        String[] fileUrls = {
                "http://example.com/file1.zip",
                "http://example.com/file2.zip",
                "http://example.com/file3.zip",
                "http://example.com/file4.zip"
        };

        String destination = "/path/to/save/files";

        DownloadManager downloadManager = new DownloadManager();
        downloadManager.startDownload(fileUrls, destination);
    }
}

Output:

Output


How to Run the Project in IntelliJ IDEA?

To run the project on IntelliJ IDEA, follow these steps:

  • Open IntelliJ IDEA and create a new Java project.
  • Create the following package structure:
    • com.downloader
  • Add the classes (DownloadTask, DownloadUtils, DownloadManager, Main) under this package.
  • Save all files.
  • Run the DownloadManager class.
Running-the-project

Article Tags :
Practice Tags :

Similar Reads