Java URL Download nio downloadFile(String fileURL, String folderPath)

Here you can find the source of downloadFile(String fileURL, String folderPath)

Description

Downloads the file with passed URL to the passed folder http://stackoverflow.com/a/921400/318221

License

Open Source License

Parameter

Parameter Description
fileURL URL of the file that should be downloaded
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

Declaration

public static String downloadFile(String fileURL, String folderPath) 

Method Source Code


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

Related

  1. download(URL url, Path location)
  2. download(URL url, String save)
  3. downloadAsync(String url, File file)
  4. downloadFile(final String url, final String downloadPath)
  5. downloadFile(String fileName, String url)
  6. downloadFile(String inputUrl, String destination)
  7. downloadFile(String sourceUrl, File destinationFile)
  8. downloadFile(String url, File output)
  9. downloadFile(String url, String localFilePath)