tags:

views:

1229

answers:

2

I have this line in my program :

InputStream Resource_InputStream=this.getClass().getClassLoader().getResourceAsStream("Resource_Name");

But how can I get FileInputStream from it [Resource_InputStream] ?

+3  A: 

Use ClassLoader#getResource() instead.

URL resource = classLoader.getResource("Resource_Name");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);

That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just use InputStream instead.

BalusC
NB that technique won't work if the resource is in a JAR file, or on the network.
EJP
@EJP: The requirement was to use a FileInputStream which itself requires... well a local file. So Balus' answer is limited but absolutely correct.
Willi
The requirement was also to read from a resource. The two requirements can conflict.
EJP
+1  A: 

Long story short: Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.

Willi