开发者

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

开发者 https://www.devze.com 2023-04-09 08:47 出处:网络
File takes String and URI in its constructors. getClass().getResource(...) ret开发者_运维技巧urns URL and

File takes String and URI in its constructors.

getClass().getResource(...) ret开发者_运维技巧urns URL and getResourceAsStream(...) returns InputStream. Is there a way to construct a File from a resource?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号