4

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.class.getResourceAsStream(resourceName);

Community
  • 1
  • 1
user489041
  • 27,916
  • 55
  • 135
  • 204

3 Answers3

8

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).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6

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?

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
0

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.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245