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.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("https://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
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.12.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
I got a question: NetBeans tells me that the String
"https://www.google.com"
cannot be converted to an URL.Can you show the complete error message produced by NetBeans?
Hi Wayan,
Can I locate my file path like this?
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 thedemo
directory.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:
and it returns:
What causes the exception?
Appreciate your help.
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 theWEB-INF\lib
directory of your web application.