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>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
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.