Java URL Download nio downloadFile(URL url, File targetFile)

Here you can find the source of downloadFile(URL url, File targetFile)

Description

download File

License

Open Source License

Declaration

public static void downloadFile(URL url, File targetFile) throws IOException 

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.HttpURLConnection;

import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class Main {
    public static void downloadFile(URL url, File targetFile) throws IOException {
        FileOutputStream fos = new FileOutputStream(targetFile);
        url = getUrlFollowingRedirects(url);
        ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();/*from  w ww  .  j  av  a  2s .  c  om*/
    }

    public static void downloadFile(String urlString, File targetFile) throws IOException {
        downloadFile(getUrlFollowingRedirects(urlString), targetFile);
    }

    private static URL getUrlFollowingRedirects(String possibleRedirectionUrl) throws IOException {
        URL url = new URL(possibleRedirectionUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        int status = conn.getResponseCode();
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            // update the URL if we were redirected
            url = new URL(conn.getHeaderField("Location"));
        }
        return url;
    }

    private static URL getUrlFollowingRedirects(URL url) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        int status = conn.getResponseCode();
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            // update the URL if we were redirected
            url = new URL(conn.getHeaderField("Location"));
        }
        return url;
    }
}

Related

  1. downloadFile(String url, String location)
  2. downloadFile(String url, String location)
  3. downloadFile(String urlPath, String local)
  4. downloadFile(URL downloadUrl, File destination)
  5. downloadFile(URL url, File output)
  6. downloadFileNIO(FileChannel fileChannel, SocketChannel socketChannel)
  7. downloadFileToDirectory(String url, File destination)
  8. downloadFirstLineFromInternetQuietly(URL url)
  9. downloadFromHttpUrl(String destPkgUrl, FileOutputStream outputStream)