Java URL Load readURL(final URL url)

Here you can find the source of readURL(final URL url)

Description

Reads the data at the supplied URL and returns it as a byte array.

License

Open Source License

Parameter

Parameter Description
url to read

Exception

Parameter Description
IOExceptionif an error occurs reading data

Return

bytes read from the URL

Declaration

public static byte[] readURL(final URL url) throws IOException 

Method Source Code


//package com.java2s;
/* See LICENSE for licensing and NOTICE for copyright. */

import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class Main {
    /** Size of buffer in bytes to use when reading files. */
    private static final int READ_BUFFER_SIZE = 128;

    /**//  w  ww  .j  a v a2 s .  com
     * Reads the data at the supplied URL and returns it as a byte array.
     *
     * @param  url  to read
     *
     * @return  bytes read from the URL
     *
     * @throws  IOException  if an error occurs reading data
     */
    public static byte[] readURL(final URL url) throws IOException {
        return readInputStream(url.openStream());
    }

    /**
     * Reads the data in the supplied stream and returns it as a byte array.
     *
     * @param  is  stream to read
     *
     * @return  bytes read from the stream
     *
     * @throws  IOException  if an error occurs reading data
     */
    public static byte[] readInputStream(final InputStream is) throws IOException {
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            final byte[] buffer = new byte[READ_BUFFER_SIZE];
            int length;
            while ((length = is.read(buffer)) != -1) {
                data.write(buffer, 0, length);
            }
        } finally {
            is.close();
            data.close();
        }
        return data.toByteArray();
    }
}

Related

  1. readTextFileAtUrl(final URL url)
  2. readTextFromUrl(URL url)
  3. readTextStream(URL url, String encoding)
  4. readTextURL(URL url)
  5. readURL(final URL fileURL)
  6. readUrl(final URL url)
  7. readUrl(final URL url)
  8. readURL(String URL)
  9. readURL(String url)