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,066
  • 55
  • 130
  • 201

3 Answers3

7

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,335,956
  • 823
  • 8,931
  • 9,049
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
  • 82,182
  • 10
  • 99
  • 146
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
  • 114,030
  • 30
  • 209
  • 240