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.*;
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 {//  ww w  . j  a v a 2s . c  o m

            final URLConnection connection = createURLConnection(url);

            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 != null && !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();
    }

    public static URLConnection createURLConnection(String url) {
        try {
            final URL address = new URL(url);
            final URLConnection connection = address.openConnection();
            connection.addRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0");
            connection.setConnectTimeout(5000);
            connection.setRequestProperty("Content-Type", "image/png");
            return connection;
        } catch (IOException ex) {
            System.out.println("Error creating connection!");
            ex.printStackTrace();
        }
        return null;
    }
}

Related

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