Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Downloading Multiple Files in Java with Sequential Write Operations

Tech 1

To download multiple files from URLs and save them locally in Java, follow a structured approahc using standard I/O and networking APIs.

Step-by-step Implementation

1. Prepare a list of file URLs

Start by defining the URLs of the files you intend to download:

List<String> urls = Arrays.asList(
    "https://example.com/file1.pdf",
    "https://example.com/image.png",
    "https://example.com/data.zip"
);

2. Iterate through each URL and download the content

For each URL, open an HTTP connection, retrieve the input stream, and write the data to a local file:

String destinationDir = "./downloads/";
new File(destinationDir).mkdirs(); // Ensure the directory exists

for (String urlString : urls) {
    try {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        int status = connection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            System.err.println("Failed to download: " + urlString + " (HTTP " + status + ")");
            continue;
        }

        String filename = Paths.get(url.getPath()).getFileName().toString();
        Path outputPath = Paths.get(destinationDir, filename);

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

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

        System.out.println("Saved: " + outputPath);

    } catch (IOException e) {
        System.err.println("Error downloading " + urlString + ": " + e.getMessage());
    }
}

This implemantation uses try-with-resources to ensure streams are properly closed, extracts filenames safely using Paths, and handdles HTTP errors gracefully. The downloads occur sequentially—each file is fully written before the next one begins.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.