Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to a file stream returned from getResourceAsStream()

Tags:

I am getting a a InputStream from getResourceAsStream(), and I managed to read from the file by passing the returned InputStream to a BufferedReader.

Is there any way I can write to the file as well?

like image 800
Andreas Grech Avatar asked May 09 '10 10:05

Andreas Grech


People also ask

What is getResourceAsStream in Java?

The getResourceAsStream() method of java. lang. Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of InputStream object. Syntax: public InputStream getResourceAsStream(String resourceName)

Do I need to close getResourceAsStream?

You should always close streams (and any other Closeable, actually), no matter how they were given to you.


1 Answers

Not directly, no - getResourceAsStream() is intended to return a view on read-only resources.

If you know that the resource is a writeable file, though, you can jump through some hoops, e.g.

URL resourceUrl = getClass().getResource(path); File file = new File(resourceUrl.toURI()); OutputStream output = new FileOutputStream(file); 

This should work nicely on unix-style systems, but windows file paths might give this indigestion. Try it and find out, though, you might be OK.

like image 133
skaffman Avatar answered Sep 27 '22 18:09

skaffman