How do I create a java.io.File object from URL?

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.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 a 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.14.0</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.