Here you can find the source of downloadFile(String url, String fileName)
Parameter | Description |
---|---|
url | The URL of the remote file. |
fileName | Name to save the download file locally. |
Parameter | Description |
---|
public static boolean downloadFile(String url, String fileName) throws MalformedURLException, IOException
//package com.java2s; //License from project: Open Source License import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; public class Main { /**// w ww .j a v a 2s.c o m * Downloads the file specified by the URL. * * @param url The URL of the remote file. * @param fileName Name to save the download file locally. * @return True if the file was downloaded and false otherwise. * @throws java.net.MalformedURLException Thrown when the informed URL is invalid. */ public static boolean downloadFile(String url, String fileName) throws MalformedURLException, IOException { URL u = new URL(url); try (final InputStream is = new BufferedInputStream(u.openStream())) { try (final OutputStream os = new FileOutputStream(fileName)) { byte[] b = new byte[1024]; int len; while ((len = is.read(b, 0, b.length)) != -1) { os.write(b, 0, len); } } } catch (MalformedURLException e) { throw new MalformedURLException("Invalid URL " + url); } catch (IOException e) { throw new IOException("Error trying to access the file " + fileName, e); } return true; } }