Java URL Download downloadFile(String url)

Here you can find the source of downloadFile(String url)

Description

download File

License

Open Source License

Declaration

public static byte[] downloadFile(String url) 

Method Source Code


//package com.java2s;
import java.io.*;
import java.net.*;
import java.util.*;

public class Main {
    public static byte[] downloadFile(String url) {// download file via http
        // protocol and return
        // contents as byte array

        try {/*from w  w  w.j a v  a 2s.c  o  m*/
            ArrayList<Byte> array = new ArrayList<Byte>(); // buffer to hold
            // stream
            byte aByte; // temp variable for reading bytes
            Byte abyte; // temp variable for reading bytes

            // initialize connection
            URL yahoo = new URL(url);
            URLConnection fileLocation = yahoo.openConnection();

            BufferedInputStream bis = new BufferedInputStream(fileLocation.getInputStream());
            byte[] buff = new byte[2048];
            int bytesRead;

            // Simple read/write loop
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                for (int i = 0; i < bytesRead; i++) {
                    aByte = buff[i];
                    array.add(new Byte(aByte));
                }
            }

            // close inputstream
            bis.close();

            // trim array size to match actual content
            array.trimToSize();

            // convert from Byte[] to byte[]
            byte[] fileContents = new byte[array.size()];
            for (int i = 0; i < array.size(); i++) {
                abyte = (Byte) array.get(i);
                fileContents[i] = abyte.byteValue();
            }

            return fileContents;

        } catch (MalformedURLException u) {
            u.printStackTrace();
            return null;

        } catch (IOException i) {

            i.printStackTrace();
            return null;
        }
    }
}

Related

  1. downloadFile(final String url)
  2. downloadFile(String fileURL, String localFileName, String destinationDir)
  3. downloadFile(String fileURL, String saveDir)
  4. downloadFile(String fileURL, String savePath)
  5. downloadFile(String fileURL, String targetDirectory)
  6. downloadFile(String url, File output)
  7. downloadFile(String url, String fileName)
  8. downloadFile(String url, String fileName)
  9. downloadFile(String url, String fileName)