Here you can find the source of downloadFile(URL url, File toFile)
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 |
Parameter | Description |
---|---|
IOException | an exception |
public static void downloadFile(URL url, File toFile) throws IOException
//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(); } } }