Java URL Download downloadFile(String url, String fileName)

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

Description

Downloads the file specified by the URL.

License

Open Source License

Parameter

Parameter Description
url The URL of the remote file.
fileName Name to save the download file locally.

Exception

Parameter Description

Return

True if the file was downloaded and false otherwise.

Declaration

public static boolean downloadFile(String url, String fileName) throws MalformedURLException, IOException 

Method Source Code


//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;
    }
}

Related

  1. downloadFile(String fileURL, String savePath)
  2. downloadFile(String fileURL, String targetDirectory)
  3. downloadFile(String url)
  4. downloadFile(String url, File output)
  5. downloadFile(String url, String fileName)
  6. downloadFile(String url, String fileName)
  7. downloadFile(String url, String filePath, File parent)
  8. downloadFile(String url, String path)
  9. downloadFile(String urlPath, File file)