Java URL Load readHttpFile(final String urlStr)

Here you can find the source of readHttpFile(final String urlStr)

Description

Read a file from the specified URL

License

Open Source License

Parameter

Parameter Description
urlStr URL to read

Exception

Parameter Description
MalformedURLException If URL is invalid
IOException Error reading or closing the file

Return

Byte array containing the data

Declaration

public static byte[] readHttpFile(final String urlStr) throws MalformedURLException, IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.ByteArrayOutputStream;

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

public class Main {
    /**//from   w w w .jav a  2s  . c o  m
     * Read a file from the specified URL
     * @param urlStr URL to read
     * @return Byte array containing the data
     * @throws MalformedURLException If URL is invalid
     * @throws IOException Error reading or closing the file
     */
    public static byte[] readHttpFile(final String urlStr) throws MalformedURLException, IOException {
        // Read from the URL in 4K chunks
        URL url = new URL(urlStr);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = null;
        try {
            is = url.openStream();
            byte[] byteChunk = new byte[4096];
            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();
            }
        }

        return baos.toByteArray();
    }
}

Related

  1. readFromUrl(String urlText)
  2. readFromUrl(URL url)
  3. readFromURL(URL url)
  4. readGOMappingFile(URL filename, Set secondAttributeList)
  5. readHttpBytes(String url)
  6. readInteger(URL src, int radix)
  7. readJsonFromUrl(String urlString)
  8. readLines(final String url)
  9. readLines(final URL url)

  10. HOME | Copyright © www.java2s.com 2016