java.net.URL read stream to byte[]

Related searches

I`m trying to read an image from an URL (with the java package java.net.URL) to a byte[]. "Everything" works fine, except that the content isnt being enterely read from the stream (the image is corrupt, it doesnt contain all the image data)... The byte array is being persisted in a database (BLOB). I really dont know what the correct approach is, maybe you can give me a tip :)

This is my first approach (code formatted, removed unnecessary informations...):

URL u = new URL("http://localhost:8080/images/anImage.jpg");
int contentLength = u.openConnection().getContentLength();
Inputstream openStream = u.openStream();
byte[] binaryData = new byte[contentLength];
openStream.read(binaryData);
openStream.close();

My second approach was this one (as you'll see the contentlength is being fetched another way):

URL u = new URL(content);
openStream = u.openStream();
int contentLength = openStream.available();
byte[] binaryData = new byte[contentLength];
openStream.read(binaryData);
openStream.close();

Both of the code result in a corrupted image... I already read this post from stackoverflow

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.

Download a File From an URL in Java, Explore the different ways of downloading a file in Java. For writing the bytes read from the URL to our local file, we'll use the write() method from the FileOutputStream byte dataBuffer[] = new byte[1024]; To read the file from our URL, we'll create a new ReadableByteChannel from the URL stream:� Input Streams Java’s basic input class is java.io.InputStream: public abstract class InputStream This class provides the fundamental methods needed to read data as raw bytes. These are: public abstract … - Selection from Java Network Programming, Second Edition [Book]

Just extending Barnards's answer with commons-io. Separate answer because I can not format code in comments.

InputStream is = null;
try {
  is = url.openStream ();
  byte[] imageBytes = IOUtils.toByteArray(is);
}
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(); }
}

http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toByteArray(java.io.InputStream)

Image URL to byte array, InputStream;. import java.net.URL;. import java.util.Arrays;. import java.util. logging.Level; public byte [] recoverImageFromUrl(String urlText) throws Exception {. URL url = new while (- 1 != (n = inputStream.read(buffer))) {. read(byte[] b, int off, int len) — reads up to len bytes of data from this input stream into an array of bytes. read() — reads one byte from the file input stream. Java InputStream read text

Here's a clean solution:

private byte[] downloadUrl(URL toDownload) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {
        byte[] chunk = new byte[4096];
        int bytesRead;
        InputStream stream = toDownload.openStream();

        while ((bytesRead = stream.read(chunk)) > 0) {
            outputStream.write(chunk, 0, bytesRead);
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    return outputStream.toByteArray();
}

How to Download a File from a URL in Java, The java.net. The openStream() function works on an object of the URL class. FileOutputStream("/Users/username/Documents/file_name.txt")) { byte data[] When we use the Java IO library we work with streams that read data byte by� The following are Jave code examples for showing how to use openStream() of the java.net.URL class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.

byte[] b = IOUtils.toByteArray((new URL( )).openStream()); //idiom

Note however, that stream is not closed in the above example.

if you want a (76-character) chunk (using commons codec)...

byte[] b = Base64.encodeBase64(IOUtils.toByteArray((new URL( )).openStream()), true);

If no byte is available because the stream is at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into b. The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, equal to the length of b.

I am very surprised that nobody here has mentioned the problem of connection and read timeout. It could happen (especially on Android and/or with some crappy network connectivity) that the request will hang and wait forever.

The following code (which also uses Apache IO Commons) takes this into account, and waits max. 5 seconds until it fails:

public static byte[] downloadFile(URL url)
{
    try {
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.connect(); 

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(conn.getInputStream(), baos);

        return baos.toByteArray();
    }
    catch (IOException e)
    {
        // Log error and return null, some default or throw a runtime exception
    }
}

The read bytes are still avilable * in the stream * * @param buffer the destination buffer to which read the data * @param offset the start offset in the destination <code>buffer</code> * @aram length how many bytes to read from the stream to buff.

How to read an http input stream. Ask Question Asked 8 years, 4 months ago. Active 3 years, 9 months ago. Viewed 108k times 44. 9. The code

C# (CSharp) NetworkStream.ReadByte - 30 examples found. These are the top rated real world C# (CSharp) examples of NetworkStream.ReadByte extracted from open source projects.

After you've successfully created a URL, you can call the URL's openStream() method to get a stream from which you can read the contents of the URL. The openStream() method returns a java.io.InputStream object, so reading from a URL is as easy as reading from an input stream.

Comments
  • Please never write an empty catch-block, not even in an example! Put at least e.printStackTrace() there! Examples have a tendency to become production code and we all have to work with that later on.
  • You're absolutely right; thanks for pointing that out. I've added more meaningful exception handling to the example.
  • Use commons.apache.org/io/api-1.4/org/apache/commons/io/… . This will make code look much cleaner.
  • Thx for your answer, your approach did work :) I have to write the data bit by bit (or a defined chunk value) to a ByteArrayOutputStream (which will on end be outputted with .toByteArray(), that was my fault...
  • In my app this code hangs on is.read(byteChunk) in some situations and never continious.
  • Thats another nice solution, but I will use the first one (because we wont include too much external libs).
  • this solution does not work for me - Server returned HTTP response code: 403 for URL: templatelab.com/wp-content/uploads/2015/11/Coupon-50.jpg
  • Don't forget to call the close method on 'stream' to release the used resources.
  • Thx for your answer. I omit the try/catch in my code posting. But how can I know the exact length of the stream? I have to allocate the byte[], so I do have to provide a length. Allocate a fixed length (say 1024) and reading from an position to an offset, check if stream contains data, copying to a new array, merging all byte[] couldnt be the best solution...