How do I copy a URL into a file?

The code snippet below show 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.example.commons.io;

import org.apache.commons.io.FileUtils;

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

public class URLToFile {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://www.google.com");
            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

<!-- http://repo1.maven.org/maven2/commons-io/commons-io/2.5/commons-io-2.5.jar -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

6 Comments

  1. Hi Brian,

    Yes, you can create File object using the relative path. In your example, the file path will be on the parent of your current working directory, under the demo directory.

    Reply
  2. Thanks for the reply.

    I have another issue now. I am trying to implement your tutorial on my JSP but it doesn’t work as compared to the java class. I have the following codes:

    <%@ page import="org.w3c.dom.*"%>
    <%@ page import="javax.xml.parsers.*"%>
    <%@ page import="java.io.File"%>
    <%@ page import="java.io.IOException"%>
    <%@ page import="java.net.URL"%>
    <%@ page import="org.apache.commons.io.*"%>
    
    <%
    try {
        URL url = new URL("http://10.12.123.12:1234/jspdemo/xmldata/xml_agency.jsp");
        File destination = new File("agencies.xml");
    
        // Copy bytes from the URL to the destination file.
        FileUtils.copyURLToFile(url, destination);
    
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    %>
    

    and it returns:

    Aug 30, 2017 9:25:37 AM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet [jsp] in context with path [/jspdemo] threw exception 
    [Unable to compile class for JSP: 
    
    An error occurred at line: 15 in the jsp file: /ReadXML.jsp
    FileUtils cannot be resolved
    

    What causes the exception?

    Appreciate your help.

    Reply
  3. Hi Brian,

    The error said that it cannot resolved the FileUtils class. Make sure you have the Apache Commons IO library in your web application. In should be in the WEB-INF\lib directory of your web application.

    Reply

Leave a Reply