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
🌐
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(); } }
🌐
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 ....
🌐
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-... commons.apache.org/proper/commons-io/ In 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....
🌐
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 - As we see above, readFileToByteArray() reads the content of the specified file into a byte array in a straightforward way.
🌐
Mkyong
mkyong.com › home › java › java – how to convert file to byte[]
Java - How to convert File to byte[] - Mkyong.com
September 17, 2020 - In Java, we can use `Files.readAllBytes(path)` to convert a `File` object into a `byte[]`.
Top answer
1 of 3
12

Just in case these small changes make a difference, try this:

public static ByteBuffer getAsByteArray(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    // Since you get a URLConnection, use it to get the InputStream
    InputStream in = connection.getInputStream();
    // Now that the InputStream is open, get the content length
    int contentLength = connection.getContentLength();

    // To avoid having to resize the array over and over and over as
    // bytes are written to the array, provide an accurate estimate of
    // the ultimate size of the byte array
    ByteArrayOutputStream tmpOut;
    if (contentLength != -1) {
        tmpOut = new ByteArrayOutputStream(contentLength);
    } else {
        tmpOut = new ByteArrayOutputStream(16384); // Pick some appropriate size
    }

    byte[] buf = new byte[512];
    while (true) {
        int len = in.read(buf);
        if (len == -1) {
            break;
        }
        tmpOut.write(buf, 0, len);
    }
    in.close();
    tmpOut.close(); // No effect, but good to do anyway to keep the metaphor alive

    byte[] array = tmpOut.toByteArray();

    //Lines below used to test if file is corrupt
    //FileOutputStream fos = new FileOutputStream("C:\\abc.pdf");
    //fos.write(array);
    //fos.close();

    return ByteBuffer.wrap(array);
}

You forgot to close fos which may result in that file being shorter if your application is still running or is abruptly terminated. Also, I added creating the ByteArrayOutputStream with the appropriate initial size. (Otherwise Java will have to repeatedly allocate a new array and copy, allocate a new array and copy, which is expensive.) Replace the value 16384 with a more appropriate value. 16k is probably small for a PDF, but I don't know how but the "average" size is that you expect to download.

Since you use toByteArray() twice (even though one is in diagnostic code), I assigned that to a variable. Finally, although it shouldn't make any difference, when you are wrapping the entire array in a ByteBuffer, you only need to supply the byte array itself. Supplying the offset 0 and the length is redundant.

Note that if you are downloading large PDF files this way, then ensure that your JVM is running with a large enough heap that you have enough room for several times the largest file size you expect to read. The method you're using keeps the whole file in memory, which is OK as long as you can afford that memory. :)

2 of 3
0

I thought I had the same problem as you, but it turned out my problem was that I assumed you always get the full buffer until you get nothing. But you do not assume that. The examples on the net (e.g. java2s/tutorial) use a BufferedInputStream. But that does not make any difference for me.

You could check whether you actually get the full file in your loop. Than the problem would be in the ByteArrayOutputStream.

Find elsewhere
🌐
How to do in Java
howtodoinjava.com › home › i/o › read file to byte[] in java
Read File to Byte[] in Java
December 14, 2022 - Learn reading data from files into a byte array in Java using NIO Files, FileInputStream, Commons IO FileUtils, and Guava ByteStreams classes.
🌐
w3resource
w3resource.com › java-exercises › io › java-io-exercise-10.php
Java - Read contents from a file into byte array
May 19, 2025 - import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; // Reading contents from a file into byte array.
🌐
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 ...
🌐
YouTube
youtube.com › codesync
java url to byte array - YouTube
Get Free GPT4o from https://codegive.com certainly! in java, if you want to convert the contents of a url into a byte array, you can make use of the `java.n...
Published   October 31, 2024
Views   3
🌐
Coderanch
coderanch.com › t › 487250 › java-io › java › Reading-Image-Local-drive-store
Reading an Image from Local drive and store to ByteArray (I/O and Streams forum at Coderanch)
I am working on a WebService that returns a Image from Server to Client. I followed different examples, and built a service that will reads a file from a URL and writes to a Byte Array.
🌐
Google Groups
groups.google.com › g › clojure › c › cB8n5uifCH8
Simple way to get image from url
(java.io.FileOutputStream. "out.file")) ; Here is our file · buffer (make-array Byte/TYPE 1024)] ; Not sure about that loop it's just prints size to repl if we don't need that we can omit that part i guess · (loop [g (.read in buffer) r 0] (if-not (= g -1) (do ·
🌐
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 - The Java NIO package offers the possibility to transfer bytes between two Channels without buffering them into the application memory. To read the file from our URL, we’ll create a new ReadableByteChannel from the URL stream:
🌐
TutorialKart
tutorialkart.com › java › java-read-file-as-bytes
Java - Read file as byte array
August 23, 2023 - Pass the file path object to readAllBytes() method of the java.nio.file.Files class. The readAllBytes() method returns byte array created from the content of the file.
🌐
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.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
7 Examples to Read File into a byte array in Java - Java Code Geeks
April 27, 2020 - The FileUtils class from org.apache.commons.io package provides a general file manipulation facility like writing to a file or reading from a file. This method is used to read the contents of a file into a byte array, and the good thing about ...