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?
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)
You should always close streams (and any other Closeable, actually), no matter how they were given to you.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With