The code snippet below uses the FileUtils.toFile(URL)
method that can be found in the Apache Commons IO library to convert a URL
into a File
. The url protocol should be file
or else null
will be returned.
package org.kodejava.commons.io;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
public class URLToFileObject {
public static void main(String[] args) throws Exception {
// FileUtils.toFile(URL url) convert from URL the File.
String data = FileUtils.readFileToString(Objects.requireNonNull(
FileUtils.toFile(URLToFileObject.class.getResource("/data.txt"))),
StandardCharsets.UTF_8);
System.out.println("data = " + data);
// Creates a URL with file protocol and convert it into File object.
File file = FileUtils.toFile(URI.create("file:///D:/data.txt").toURL());
data = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
System.out.println("data = " + data);
}
}
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