Java URL Download nio download(String from, String to)

Here you can find the source of download(String from, String to)

Description

download

License

Open Source License

Declaration

public static void download(String from, String to) throws IOException 

Method Source Code


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

import java.io.BufferedInputStream;

import java.io.IOException;
import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class Main {
    public static void download(String from, String to) throws IOException {
        download(newURL(from), Paths.get(to));
    }//from   w  ww.  ja  v a2s  .c  o m

    private static void download(URL from, Path to) throws IOException {
        to.getParent().toFile().mkdirs();
        if (to.toFile().exists()) {
            return;
        }
        Path part = Paths.get(to.toString() + ".part");
        InputStream in = newInputStream(from);
        Files.copy(in, part, StandardCopyOption.REPLACE_EXISTING);
        Files.move(part, to, StandardCopyOption.REPLACE_EXISTING);
    }

    public static URL newURL(String location) throws IOException {
        return newURI(location).toURL();
    }

    public static boolean exists(String location) {
        try {
            return exists(newURL(location));
        } catch (IOException e) {
            return false;
        }
    }

    public static boolean exists(URL url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");
            return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
        } catch (IOException e) {
            return false;
        }
    }

    private static BufferedInputStream newInputStream(URL url) throws IOException {
        return new BufferedInputStream(url.openStream());
    }

    public static URI newURI(String location) throws IOException {
        try {
            return URI.create(location);
        } catch (IllegalArgumentException e) {
            throw new IOException("malformed uri: " + location, e);
        }
    }
}

Related

  1. canDownload(String filePath)
  2. download(File dist, URL src)
  3. download(String link, File destFile)
  4. download(String url, File output)
  5. download(String url, String destPath)
  6. download(String url, String inputFile, String outputPath, String outputFile)