How do I create File object from URL?

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.




public class URLToFileObject {
    public static void main(String[] args) throws Exception {
        // FileUtils.toFile(URL url) convert from URL the File.
        String data = FileUtils.readFileToString(FileUtils.toFile(
                URLToFileObject.class.getResource("/data.txt")), "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, "UTF-8");
        System.out.println("data = " + data);

Maven Dependencies

<!-- -->

Leave a Reply

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