In Java, how can I construct a File from a resource?

file-io, java

Solution

You can't. At least not in the standard case where the resource is inside a Jar. Java File Objects must point to actual file system objects (files and folders), whereas a resource is an entry in a Jar File. Trying to construct a File from a Jar resource URI will result in an exception:

`java.lang.IllegalArgumentException`: URI is not hierarchical

Problem

File takes String and URI in its constructors. `getClass().getResource(...)` returns URL and `getResourceAsStream(...)` returns InputStream. Is there a way to construct a File from a resource?

Original source