Here you can find the source of readHttpFile(final String urlStr)
Parameter | Description |
---|---|
urlStr | URL to read |
Parameter | Description |
---|---|
MalformedURLException | If URL is invalid |
IOException | Error reading or closing the file |
public static byte[] readHttpFile(final String urlStr) throws MalformedURLException, IOException
//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(); } }