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
<!-- https://search.maven.org/remotecontent?filepath=commons-io/commons-io/2.11.0/commons-io-2.11.0.jar -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022
- How do I convert CSV file to or from JSON file? - February 13, 2022