Here you can find the source of downloadFile(String fileURL, String folderPath)
Downloads the file with passed URL to the passed folder http://stackoverflow.com/a/921400/318221
Parameter | Description |
---|---|
fileURL | URL of the file that should be downloaded |
folderPath | The path to which this file should be saved |
public static String downloadFile(String fileURL, String folderPath)
//package com.java2s; //License from project: Open Source License import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; public class Main { /**//from w w w. ja v a2 s . c o m * Downloads the file with passed URL to the passed folder * http://stackoverflow.com/a/921400/318221 * * @param fileURL URL of the file that should be downloaded * @param folderPath The path to which this file should be saved * @return The local full path of the downloaded file, empty string is returned if a problem occurs */ public static String downloadFile(String fileURL, String folderPath) { //Extract filename only without full path int lastSlashPos = fileURL.lastIndexOf('/'); if (lastSlashPos < 0) { return null; } String fullFileName = folderPath + fileURL.substring(lastSlashPos + 1); //Create parent folder if it does not already exist File file = new File(fullFileName); file.getParentFile().mkdirs(); URL url; try { url = new URL(fileURL); } catch (MalformedURLException e) { return null; } try (ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(file);) { fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (FileNotFoundException e) { return null; } catch (IOException e) { return null; } return fullFileName; } }