Java URL Download downloadFile(URL url, File toFile)

Here you can find the source of downloadFile(URL url, File toFile)

Description

Downloads a remote file given by an URL to the given local file

License

Apache License

Parameter

Parameter Description
url The URL that specifies the location of the file to download
toFile The local file to which the remote file will be downloaded

Exception

Parameter Description
IOException an exception

Declaration

public static void downloadFile(URL url, File toFile) throws IOException 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.io.BufferedOutputStream;
import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStream;

import java.io.OutputStream;

import java.net.URL;
import java.net.URLConnection;

public class Main {
    /**/*www .j av a2 s .c  o  m*/
     * Downloads a remote file given by an URL to the given local file
     * @param url The URL that specifies the location of the file to download
     * @param toFile The local file to which the remote file will be downloaded
     * @throws IOException
     */
    public static void downloadFile(URL url, File toFile) throws IOException {
        OutputStream out = null;
        URLConnection conn = null;
        InputStream in = null;
        out = new BufferedOutputStream(new FileOutputStream(toFile));
        conn = url.openConnection();
        conn.setUseCaches(false);
        in = conn.getInputStream();
        byte[] buffer = new byte[1024];
        int numRead;
        long numWritten = 0;
        while ((numRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, numRead);
            numWritten += numRead;
        }

        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

Related

  1. downloadFile(String urlString)
  2. downloadFile(String urlString, String filename)
  3. downloadFile(String urlToDownload, File locationToStore)
  4. downloadFile(URL fileUrl, File out)
  5. downloadFile(URL theURL, String filePath)
  6. downloadFile(URL url, String name)
  7. downloadFile(URL url, String path, String fileName)
  8. downloadFileAndRetry(final File file, final URL url, final int retry)
  9. downloadFileFromInternet(String remoteUrl)