开发者

Convert InputStream into FileInputStream

开发者 https://www.devze.com 2023-02-18 19:51 出处:网络
I have read this post How to convert InputStream to FileInputStream on converting a InputStream into a FileInputStream. However, the answer does not work if you are using a resource that is in a jar f

I have read this post How to convert InputStream to FileInputStream on converting a InputStream into a FileInputStream. However, the answer does not work if you are using a resource that is in a jar file. Is there another way to do it.

I need to do this to get the FileChannel from a call to Object.cl开发者_运维百科ass.getResourceAsStream(resourceName);


You can't, without basically writing to a file. Unless there's a file, there can't be a FileInputStream or a FileChannel. If at all possible, make sure your code is agnostic to the input source - design it in terms of InputStream and ByteChannel (or whatever kind of channel is most appropriate).


From the InputStream returned by Class.getResourceAsStream(), you can make a Channel with Channels.newChannel( InputStream ).

This is not the FileChannel you requested, but it is still a Channel. Is it sufficient to meet your needs?


If you really need a file and you know that the resource is not inside a jar or loaded remotely, then you can use getResource instead.

URL resourceLocation = Object.class.getResource(resourcePath);
if (resourceLocation == null) { throw new FileNotFoundException(resourcePath); }
File myFile = new File(resourceLocation.toURI());

If you don't absolutely need a FileChannel or can't make assumptions about how your classpath is laid out, then Andy Thomas-Cramer's solution is probably the best.

0

精彩评论

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

关注公众号