There's no guarantee that the content length you're provided is actually correct. Try something akin to the following:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
  is = url.openStream ();
  byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
  int n;

  while ( (n = is.read(byteChunk)) > 0 ) {
    baos.write(byteChunk, 0, n);
  }
}
catch (IOException e) {
  System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
  e.printStackTrace ();
  // Perform any other exception handling that's appropriate.
}
finally {
  if (is != null) { is.close(); }
}

You'll then have the image data in baos, from which you can get a byte array by calling baos.toByteArray().

This code is untested (I just wrote it in the answer box), but it's a reasonably close approximation to what I think you're after.

Answer from RTBarnard on Stack Overflow
🌐
Google Groups
groups.google.com › g › piepronchingti › c › u6grw6zPkgU
Java Download File From Url To Byte Array [TOP]
That is, where each member of the byte array remains intact in its String counterpart, with no extra space required for encoding/transport. AFAIK, Array is equivalent to java's Byte[] (the boxed byte). If you want primitive byte array, use ByteArray.
🌐
Baeldung
baeldung.com › home › java › java io › download a file from an url in java
Download a File From an URL in Java | Baeldung
January 8, 2024 - We can use the Files.copy() method to read all the bytes from an InputStream and copy them to a local file: InputStream in = new URL(FILE_URL).openStream(); Files.copy(in, Paths.get(FILE_NAME), StandardCopyOption.REPLACE_EXISTING);
🌐
Dot Net Perls
dotnetperls.com › url-java
Java - URL Class Example, Download Web Page - Dot Net Perls
December 26, 2023 - Then We use a while-loop to read the InputStream into a byte array. We then append to a StringBuilder to get the total file. Result We can see that on the "Example" domain, it fetched the correct HTML document. The document is more than 1024 bytes. import java.io.IOException; import ...
🌐
Binary Coders
binarycoders.wordpress.com › 2015 › 04 › 21 › image-url-to-byte-array
Image URL to byte array - Binary Coders - WordPress.com
April 17, 2026 - package com.wordpress.binarycoders.image.recovery; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; public class ImageRecover { public byte[] recoverImageFromUrl(String urlText) throws Exception { URL url = new URL(urlText); ByteArrayOutputStream output = new ByteArrayOutputStream(); try (InputStream inputStream = url.openStream()) { int n = 0; byte [] buffer = new byte[ 1024 ]; while (-1 != (n = inputStream.read(buffer))) { output.write(buffer, 0, n); } } return output.toByteArray(); } }
🌐
amitph
amitph.com › home › java › how to download a file from url in java
How to Download a File from URL in Java - amitph
November 22, 2024 - Next, we use a bucket of byte[] to read 2048 bytes from the input stream and write it onto the output stream iteratively. This example demonstrates how we can use our own buffer (for example 2048 bytes) so that downloading large files should not consume huge memory on our system. Note: While dealing with Java File IO, we must close all the open streams and readers.
🌐
Stack Overflow
stackoverflow.com › questions › 61239747 › when-downloading-a-file-from-a-url-why-do-we-read-into-a-byte-array
java - When downloading a file from a URL, why do we read into a byte array? - Stack Overflow
April 15, 2020 - We read the data into a byte array instead of a char array or an int array because it is binary data. It might be text or a picture or a video. At the end of the day, these are all binary data that we store in bytes.
🌐
TutorialsPoint
tutorialspoint.com › java_dip › pdf › downloading_uploading_images.pdf pdf
http://www.tutorialspoint.com/java_dip/downloading_uploading_images.htm
... When you execute the given ... an image to a webserver. We convert a BufferedImage to byte array in ... We use Java class ByteArrayOutputStream, which can be found under java.io package....
Find elsewhere
🌐
GitHub
gist.github.com › 9523327
Download image file into byte array · GitHub - Gist
Learn more about clone URLs · Clone this repository at <script src="https://gist.github.com/xalexchen/9523327.js"></script> Save xalexchen/9523327 to your computer and use it in GitHub Desktop. Download ZIP · Download image file into byte array · Raw · PhotoDownloadRunnable.java ·
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-download-file-url
Java Download File from URL | DigitalOcean
August 4, 2022 - downloadUsingStream: In this method of java download file from URL, we are using URL openStream method to create the input stream. Then we are using a file output stream to read data from the input stream and write to the file. downloadUsingNIO: In this download file from URL method, we are ...
🌐
STechies
stechies.com › download-file-from-url-java
How to Download a File from a URL in Java
Within the try block, set the URL and the URLConnection using getInputStream(). The following catch block will handle any input-output exception and execute the printStackTrace(). The finally block (which executes automatically as a mandatory part of the program) will display the message “URL's File downloaded.” · Java NIO (abbreviated as New IO) is an alternative input-output Java API that also comes as a Java package. The NIO acts as an alternative to the standard Java IO and Java Networking API. While using the Java IO library, the streams read the data byte by byte.
🌐
Simplesolution
simplesolution.dev › java-read-content-from-url-into-byte-array-using-apache-commons-io
Read Content from URL into Byte Array in Java using Apache Commons IO
<dependency> <groupId>commons-... the following Java program we use the IOUtils.toByteArray() method with a given URL object to read the content of the URL as a byte array....
🌐
GitHub
gist.github.com › xalexchen › 9523327
Download image file into byte array · GitHub
Learn more about clone URLs · Clone this repository at &lt;script src=&quot;https://gist.github.com/xalexchen/9523327.js&quot;&gt;&lt;/script&gt; Save xalexchen/9523327 to your computer and use it in GitHub Desktop. Download ZIP · Download image file into byte array · Raw · PhotoDownloadRunnable.java ·
🌐
Baeldung
baeldung.com › home › java › java io › convert file to byte array in java
Convert File to Byte Array in Java | Baeldung
January 5, 2024 - In a nutshell, we use the toByteArray() method to get a byte array containing all the bytes from the given file.
🌐
Java2s
java2s.com › example › android › file-input-output › read-from-url-and-return-byte-array.html
Read from URL and return Byte Array - Android File Input Output
Read from URL and return Byte Array ... import java.net.URL; import java.net.URLConnection; public class Main { public static byte[] getHtmlByteArray(final String url) { URL htmlUrl = null;//w w w ....
🌐
CodeJava
codejava.net › java-se › networking › use-httpurlconnection-to-download-file-from-an-http-url
Java HttpURLConnection to download file from an HTTP URL
July 18, 2019 - Open connection on the URL object – which would return an HttpURLConnection object if the URL is an HTTP URL. Open the input stream of the opened connection. Create an output stream to save file to disk. Repeatedly read array of bytes from the input stream and write them to the output stream, ...
🌐
sqlpey
sqlpey.com › java › java-download-file-from-url
Java Download File from URL: Efficient Methods Explained - …
July 22, 2025 - import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; public class BufferedStreamDownloader { public static void downloadFileFromURL(String urlString, String filename) throws IOException { BufferedInputStream in = null; FileOutputStream fout = null; try { in = new BufferedInputStream(new URL(urlString).openStream()); fout = new FileOutputStream(filename); byte[] data = new byte[1024]; int count; while ((count = in.read(data, 0, 1024)) != -1) { fout.write(data, 0, count); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } } }