Java URL Download downloadFile(String url, String filePath, File parent)

Here you can find the source of downloadFile(String url, String filePath, File parent)

Description

Download a provided file

License

Open Source License

Parameter

Parameter Description
url a parameter
filePath a parameter
parent a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static File downloadFile(String url, String filePath, File parent) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedOutputStream;

import java.io.File;
import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class Main {
    /**//from  w w  w.  j a v a 2s.c o  m
     * Download a provided file 
     * 
     * @param url
     * @param filePath
     * @param parent
     * @return
     * @throws IOException
     */
    public static File downloadFile(String url, String filePath, File parent) throws IOException {
        File file = null;
        if (url != null && filePath != null) {
            if (parent != null) {
                file = new File(parent.getAbsolutePath() + filePath);
            } else {
                file = new File(filePath);
            }

            if (!file.exists()) {
                File parentDir = file.getParentFile();
                if (!parentDir.exists()) {
                    if (!parentDir.mkdirs()) {
                        throw new IOException("Unable to create directory structure");
                    }
                }
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    System.err.println("Error occurred while creating file");
                    throw e;
                }
                URL u = new URL(url);
                try (InputStream is = u.openStream();
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
                    int b;
                    while ((b = is.read()) != -1) {
                        bos.write(b);
                    }
                }
            }
        }
        return file;
    }
}

Related

  1. downloadFile(String url)
  2. downloadFile(String url, File output)
  3. downloadFile(String url, String fileName)
  4. downloadFile(String url, String fileName)
  5. downloadFile(String url, String fileName)
  6. downloadFile(String url, String path)
  7. downloadFile(String urlPath, File file)
  8. downloadFile(String urlString)
  9. downloadFile(String urlString, String filename)