The code snippet below use the FileUtils.toFile(URL)
method that can be found in the 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.URL;
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(new URL("file:///D:/demo.txt"));
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.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