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