Java URL Download nio downloadFile(String url, String location)

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

Description

download File

License

Open Source License

Declaration

public static boolean downloadFile(String url, String location) 

Method Source Code

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class Main {
    public static boolean downloadFile(String url, String location) {
        try {//from www  .  j av  a2s  . c  o  m
            final URLConnection connection = new URL(url).openConnection();
            connection.addRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0");

            final int contentLength = connection.getContentLength();
            final File destination = new File(location);

            if (destination.exists()) {
                final URLConnection savedFileConnection = destination.toURI().toURL().openConnection();
                if (savedFileConnection.getContentLength() == contentLength) {
                    return true;
                }
            } else {
                final File parent = destination.getParentFile();
                if (!parent.exists())
                    parent.mkdirs();
            }

            final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());

            final FileOutputStream fos = new FileOutputStream(destination);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();

        } catch (IOException exception) {
            exception.printStackTrace();
            return false;
        }

        System.out.println(url + "->" + location);
        return new File(location).exists();
    }
}

Related

  1. downloadFile(String fileURL, String folderPath)
  2. downloadFile(String inputUrl, String destination)
  3. downloadFile(String sourceUrl, File destinationFile)
  4. downloadFile(String url, File output)
  5. downloadFile(String url, String localFilePath)
  6. downloadFile(String url, String location)
  7. downloadFile(String urlPath, String local)
  8. downloadFile(URL downloadUrl, File destination)
  9. downloadFile(URL url, File output)