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?
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?
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.
Is there any way I can write to the file as well?
Who says it's a file? The whole point of getResourceAsStream()
is to abstract that away because it might well not be true. Specifically, the resource may be situated in a JAR file, may be read from a HTTP server, or really anything that the implementer of the ClassLoader
could imagine.
You really shouldn't want to write to a resource that's part of your program distribution. It's conceptually the wrong thing to do in most cases. Settings or User-specific data should go to the Preferences API or the user's home directory.