How do I copy a URL into a file?

The code snippet below shows you how to use the FileUtils.copyURLToFile(URL, File) method of the Apache Commons IO library to help you to copy the contents of a URL directly into a file.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;

public class URLToFile {
    public static void main(String[] args) {
        try {
            URL url = URI.create("https://www.google.com").toURL();
            File destination = new File("google.html");

            // Copy bytes from the URL to the destination file.
            FileUtils.copyURLToFile(url, destination);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.16.1</version>
</dependency>

Maven Central