Here you can find the source of copyURLToFile(final URL source, final File destination)
public static void copyURLToFile(final URL source, final File destination) throws IOException
//package com.java2s; /**/*from ww w .j av a 2 s. c om*/ * Copyright (C) 2011 Ovea <dev@ovea.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.net.URL; public class Main { private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; public static void copyURLToFile(final URL source, final File destination) throws IOException { if (destination.getParentFile() != null && !destination.getParentFile().exists()) { destination.getParentFile().mkdirs(); } // Make sure we can write to destination if (destination.exists() && !destination.canWrite()) { throw new IllegalArgumentException("Unable to open file " + destination + " for writing."); } InputStream in = new BufferedInputStream(source.openStream()); copy(in, destination); in.close(); } public static void copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int n; while (-1 != (n = in.read(buffer))) { out.write(buffer, 0, n); } } public static void copy(Reader input, Writer output) throws IOException { char[] buffer = new char[DEFAULT_BUFFER_SIZE]; int n; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } } public static void copy(InputStream in, File dest) throws IOException { OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { copy(in, out); } finally { out.flush(); out.close(); } } public static String read(File file) throws IOException { return read(file.toURI().toURL()); } public static String read(URL file) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(file.openStream())); try { StringWriter sw = new StringWriter(); copy(input, sw); return sw.toString(); } finally { input.close(); } } }