Java URL Download downloadToFile(URL url, File downloadFile)

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

Description

download To File

License

Open Source License

Declaration

public static void downloadToFile(URL url, File downloadFile) throws Exception 

Method Source Code

//package com.java2s;
/**//from  w  ww .  ja  v  a 2  s.  c  om
 * @(#)FileUtil.java
 *
 * Copyright (2003) Bro3
 * 
 * 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 2, or 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.
 * 
 * You should have received a copy of the GNU General Public License along with 
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Boston, MA 02111.
 * 
 * Contact: bro3@users.sourceforge.net
 **/

import java.io.*;

import java.net.URL;

public class Main {
    public static void downloadToFile(URL url, File downloadFile) throws Exception {

        long startTime = System.currentTimeMillis();

        System.out.println(String.format("Begin download from %s...\n", url));

        url.openConnection();
        InputStream reader = url.openStream();

        /*
        * Setup a buffered file writer to write
        * out what we read from the website.
        */

        File parentFile = downloadFile.getParentFile();
        if (!parentFile.exists())
            parentFile.mkdirs();

        FileOutputStream writer = new FileOutputStream(downloadFile);
        byte[] buffer = new byte[153600];
        int totalBytesRead = 0;
        int bytesRead = 0;

        System.out.println("Reading file 150KB blocks at a time.\n");

        while ((bytesRead = reader.read(buffer)) > 0) {
            writer.write(buffer, 0, bytesRead);
            buffer = new byte[153600];
            totalBytesRead += bytesRead;
        }

        long endTime = System.currentTimeMillis();

        System.out.println("Done. " + (new Integer(totalBytesRead).toString()) + " bytes read ("
                + (new Long(endTime - startTime).toString()) + " millseconds).\n");
        writer.close();
        reader.close();
    }
}

Related

  1. downloadTextFromUrl(String url)
  2. downloadTo(String url, String filename)
  3. downloadToDirectory(URL url, String directoryName)
  4. downloadToFile(String url, File file)
  5. downloadToFile(URL source, File dest)
  6. downloadToFile(URL url, File file)
  7. downloadToLocalFile(File targetFile, URL requestedURL, Proxy proxy)
  8. downloadToString(String url)
  9. downloadURL(String addr, File outFile)