Here you can find the source of downloadFile(URL url, File targetFile)
public static void downloadFile(URL url, File targetFile) throws IOException
//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; } }