Convert InputStream to FileInputStream

I read this post How to convert InputStream to FileInputStream to convert InputStream to FileInputStream. However, the answer does not work if you use a resource that is in the jar file. Is there any other way to do this.

I need to do this to get FileChannelfrom a call Object.class.getResourceAsStream(resourceName);

+3
source share
3 answers

You cannot, without writing to a file. If there is no file, it cannot be FileInputStreamor FileChannel. If at all possible, make sure that your code is agnostic for the input source - create it in terms of InputStreamand ByteChannel(or some other channel is most suitable).

+6
source

InputStream, Class.getResourceAsStream(), Channels.newChannel(InputStream).

FileChannel, - . ?

+6

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

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

If you do not need absolutely FileChannelor cannot make assumptions about how your class path is laid out, then Andy Thomas-Cramer's decision is probably the best.

0
source

All Articles