Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

file-io

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?

like image 382
deltanovember Avatar asked Feb 13 '26 19:02

deltanovember


2 Answers

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

like image 99
Sean Patrick Floyd Avatar answered Feb 16 '26 09:02

Sean Patrick Floyd


Is there a way to construct a File from a resource?

Strictly speaking, no. But if you really need a File (to pass to an API), then you can create a temporary file and write the InputStream to that.

like image 38
Tim Bender Avatar answered Feb 16 '26 09:02

Tim Bender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!