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.
精彩评论