Downloading Multiple Files in Java with Sequential Write Operations
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.