Java URL Load loadByteArray(URL url)

Here you can find the source of loadByteArray(URL url)

Description

Load a byte [] from a URL.

License

Open Source License

Parameter

Parameter Description
url The URL to open the stream from.

Exception

Parameter Description
IOException On URL read error.

Return

A byte array representing the resource defined by the URL.

Declaration

public static byte[] loadByteArray(URL url) throws IOException 

Method Source Code


//package com.java2s;
/*//from   w w  w  .  j a  va2s. co m
 *
 * Copyright (c) 2012 Certus Technology Associates Limited.
 * http://www.certus-tech.com/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
    
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.net.URL;

public class Main {
    /**
     * Load a byte [] from a URL. This method can be used to read a file or other URL into a byte array.
     *
     * @param url The URL to open the stream from.
     * @return A byte array representing the resource defined by the URL.
     * @throws IOException On URL read error.
     */
    public static byte[] loadByteArray(URL url) throws IOException {
        // Open an input stream from the URL
        InputStream iStream = new BufferedInputStream(url.openStream());
        // Open an output byte stream to write to.
        ByteArrayOutputStream oStream = new ByteArrayOutputStream();
        // Create a tmp buffer.
        byte[] blk = new byte[8192];
        int bytesRead;
        while ((bytesRead = iStream.read(blk)) != -1) {
            oStream.write(blk, 0, bytesRead);
        }
        iStream.close();
        // Return the bytes
        return oStream.toByteArray();
    }
}

Related

  1. load(String fileOrURL)
  2. load(URL pUrl)
  3. load(URL url)
  4. load(URL url)
  5. load(URL url, boolean allowCache)
  6. loadFile(String url)
  7. loadFile(URL resource)
  8. loadFile(URL url)
  9. loadFileNoArray(URL f)