This project demonstrates how to download binary content (an image) from a remote web server using Java's networking capabilities. It combines the java.net.URL class for establishing a connection with the java.nio.file.Files utility for streamlined file saving.
- Source: Connect to
https://httpbin.org/image/png. - Target: Save the file as
image01.pngin the root directory. - Connection: Use
URL.openStream()to retrieve the data stream. - Persistence: Use
Files.copy(InputStream, Path)for efficient data transfer. - Goal: Learn the basics of web-to-disk data streaming.
- Java 11+ (using
Path.of())
The program opens an InputStream directly from the URL. This stream acts as a pipe through which the image data flows. Instead of manually reading bytes into a buffer, we use Files.copy(), which efficiently pipes the input stream directly to the specified file path.
A new file image01.png appears in the project folder. When opened, it displays a valid PNG image.
Image successfully downloaded: image01.png
Project Structure:
├── image01.png
└── src src/com/yurii/pavlenko/
└── Solution.java
Code
package com.yurii.pavlenko;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class Solution {
public static void main(String[] args) {
String imageUrl = "https://httpbin.org/image/png";
String fileName = "image01.png";
Path destination = Path.of(fileName);
try (InputStream inputStream = new URL(imageUrl).openStream()) {
Files.copy(inputStream, destination, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Image successfully downloaded: " + fileName);
} catch (IOException e) {
System.out.println("Error during download: " + e.getMessage());
}
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT